Skip to the code

Time a function with User Timing

Write timed(name, fn), which calls fn(), records how long it took with User Timing, and returns what fn returned. The tea shop wraps its slow spots in it, like timed("menu:render", () => renderMenu(teas)).

Before calling fn, make a mark named name + ":start". When fn is done, make a mark named name + ":end", then a measure named name from the start mark's time to the end mark's, then remove both marks with performance.clearMarks(), leaving every other mark. The measure stays: DevTools shows it in the Timings track, and an observer of measure entries can send it.

fn is done when it returns, or, if it returns a promise (anything with a then method), when that promise settles; then timed returns a promise of the same value or error. A function that throws, or a promise that rejects, is measured too, and the error reaches the caller as it was. Calls with the same name can overlap, like two searches at once, and each call's measure must still run from its own start to its own end.

const html = timed("menu:render", () => renderMenu(teas)); // what renderMenu returned
const reviews = await timed("reviews:load", () => fetch("/reviews").then((response) => response.json()));
performance.getEntriesByName("reviews:load", "measure")[0].duration; // how long the reviews took, in ms

What the tests check

  1. times a synchronous function with a measure, and returns what it returned
    const clock = useFakeTimers();
    usePerformance();
    clock.tick(1000);
    const total = timed("menu:render", () => {
      clock.spend(30);
      return 12;
    });
    expect(total).toBe(12);
    expect(performance.getEntriesByType("measure").map((measure) => [measure.name, measure.startTime, measure.duration])).toEqual([["menu:render", 1000, 30]]);
    
  2. marks the start and the end, then clears both marks
    const clock = useFakeTimers();
    usePerformance();
    const marks = [];
    new PerformanceObserver((list) => {
      for (const mark of list.getEntries()) marks.push([mark.name, mark.startTime]);
    }).observe({ type: "mark" });
    let during = null;
    timed("cart:total", () => {
      during = performance.getEntriesByName("cart:total:start", "mark").length;
      clock.spend(5);
    });
    expect(during).toBe(1);
    expect(marks).toEqual([["cart:total:start", 0], ["cart:total:end", 5]]);
    expect(performance.getEntriesByType("mark")).toEqual([]);
    
  3. leaves the page's other marks alone
    const clock = useFakeTimers();
    usePerformance();
    performance.mark("app:ready");
    timed("cart:total", () => clock.spend(5));
    expect(performance.getEntriesByType("mark").map((mark) => mark.name)).toEqual(["app:ready"]);
    expect(performance.getEntriesByType("measure").map((measure) => measure.name)).toEqual(["cart:total"]);
    
  4. times an async function until its promise settles, and resolves with its value
    const clock = useFakeTimers();
    usePerformance();
    const reviews = timed("reviews:load", async () => {
      await new Promise((resolve) => setTimeout(resolve, 250));
      return ["Lovely mint", "Smoky lapsang"];
    });
    expect(reviews).toBeInstanceOf(Promise);
    expect(performance.getEntriesByType("measure")).toEqual([]);
    await clock.runAllAsync();
    expect(await reviews).toEqual(["Lovely mint", "Smoky lapsang"]);
    expect(performance.getEntriesByType("measure").map((measure) => [measure.name, measure.startTime, measure.duration])).toEqual([["reviews:load", 0, 250]]);
    expect(performance.getEntriesByType("mark")).toEqual([]);
    
  5. a function that throws and a promise that rejects are measured too, and the error reaches the caller
    const clock = useFakeTimers();
    usePerformance();
    expect(() =>
      timed("menu:parse", () => {
        clock.spend(4);
        throw new SyntaxError("The menu isn't valid JSON");
      }),
    ).toThrow(SyntaxError);
    const outcome = timed("reviews:load", () => new Promise((resolve, reject) => setTimeout(() => reject(new Error("Offline")), 80))).then(
      () => "resolved",
      (error) => error.message,
    );
    await clock.runAllAsync();
    expect(await outcome).toBe("Offline");
    expect(performance.getEntriesByType("measure").map((measure) => [measure.name, measure.startTime, measure.duration])).toEqual([
      ["menu:parse", 0, 4],
      ["reviews:load", 4, 80],
    ]);
    expect(performance.getEntriesByType("mark")).toEqual([]);
    
  6. overlapping calls with the same name each get a measure of their own
    const clock = useFakeTimers();
    usePerformance();
    const later = (value, ms) => () => new Promise((resolve) => setTimeout(() => resolve(value), ms));
    const green = timed("search", later(["Sencha", "Gyokuro"], 300));
    clock.tick(100);
    const mint = timed("search", later(["Moroccan mint"], 50));
    await clock.runAllAsync();
    expect(await green).toEqual(["Sencha", "Gyokuro"]);
    expect(await mint).toEqual(["Moroccan mint"]);
    expect(performance.getEntriesByType("measure").map((measure) => [measure.name, measure.startTime, measure.duration])).toEqual([
      ["search", 0, 300],
      ["search", 100, 50],
    ]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).