CodeBlanks Logo Icon CodeBlanks

Performance measurement

JavaScript course · Expert · Lesson 7/63

Learn to measure an operation's duration with performance.now and profiling.

Measuring duration

To measure how long an operation takes, use performance.now(). It returns the time elapsed since the page loaded, in milliseconds, with high resolution.

To benchmark, capture a value before and after the work and subtract them. This pattern is common in benchmark tests.

Browser profiler tools also show per-function durations, but for in-code measurement performance.now() is the most accurate choice.

Exercise Timing function

Write a function named measure. It takes fn, runs it, and returns the elapsed time in milliseconds using performance.now().

Show example solution
Capture start and end with performance.now(), then return the difference.

Example solution:
function measure(fn) {
  const start = performance.now();
  fn();
  const end = performance.now();
  return end - start;
}

Reliable measurement

To compare several operations, write a measure function that runs the given work and returns the elapsed time.

When reading results, prefer an average over many runs rather than a single one. A single run can be misleading because of garbage collection or background tasks.

Test yourself

  1. What does performance.now() return?

    • A Date object
    • Time in milliseconds
    • Uptime in seconds
    • Memory usage
    Show answer

    Time in milliseconds — Correct! performance.now() returns milliseconds since the page loaded.

  2. Time measurement

    const start = ____;
    heavyWork();
    const end = performance.now();
    console.log(end - start);
    Show answer
    const start = performance.now();
    heavyWork();
    const end = performance.now();
    console.log(end - start);
  3. Match the timing APIs

    performance.now
    duration in ms
    Date.now
    unix timestamp
    console.time
    simple timer
    performance.mark
    named mark

All lessons in Expert