@FahadM to JavaScriptEnglish • 4 days ago

How do you accurately benchmark and measure a function's execution time in JavaScript?

message-square
0
1
How do you accurately benchmark and measure a function's execution time in JavaScript?
@FahadM to JavaScriptEnglish • 4 days ago

To accurately benchmark and measure a function’s execution time in JavaScript, use a high-resolution monotonic clock—performance.now() in browsers/Node/Deno/Bun or process.hrtime.bigint() in Node.js (never Date.now(), which has coarse resolution and can jump with system clock adjustments)—and run multiple iterations after a warm-up phase, taking the median (or percentiles like p50/p95) rather than a single sample or raw mean that can be skewed by JIT (Just-In-Time) compilation, garbage collection (GC) pauses, or background OS/browser scheduling. Because micro-benchmarks on tiny functions can be distorted by dead-code elimination or loop overhead, always consume the return value (e.g., accumulate into a sink variable) and compare candidate implementations under realistic inputs.


1. High-Resolution Timing with performance.now() and Warm-Up + Median

Measure elapsed time with performance.now() (sub-millisecond precision), run a brief warm-up loop so the engine’s JIT compiler optimizes hot paths, collect multiple samples, and compute the median (p50) and IQR / p95 so outlier spikes do not distort the result:

// Benchmark a synchronous function with warm-up, sink accumulation, and median/p95 stats
function benchmarkSync(fn, { iterations = 500, warmup = 50 } = {}) {
  if (typeof fn !== "function") {
    throw new TypeError("Expected fn to be a function.");
  }
  if (!Number.isInteger(iterations) || iterations <= 0 || !Number.isInteger(warmup) || warmup < 0) {
    throw new RangeError("Expected positive integer iterations and non-negative integer warmup.");
  }

  // Sink prevents the engine from treating pure computations as dead code
  let sink;

  // 1. Warm-up phase so JIT tier-up and inline caches stabilize
  for (let i = 0; i < warmup; i += 1) {
    sink = fn(i);
  }

  // 2. Timed sample runs
  const durationsMs = new Array(iterations);
  for (let i = 0; i < iterations; i += 1) {
    const start = performance.now();
    sink = fn(i);
    const end = performance.now();
    durationsMs[i] = end - start;
  }

  const sorted = [...durationsMs].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  const medianMs =
    sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
  const p95Ms = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))];
  const minMs = sorted[0];
  const maxMs = sorted[sorted.length - 1];

  return {
    iterations,
    minMs,
    medianMs,
    p95Ms,
    maxMs,
    _sink: sink
  };
}

// Example usage:
const sampleData = Array.from({ length: 1000 }, (_, idx) => idx);
const stats = benchmarkSync(() => sampleData.reduce((acc, n) => acc + n, 0));
console.log(stats);
  • Prefer medianMs over meanMs: A single GC pause or OS interrupt can inflate the mean, whereas the median reflects typical steady-state execution.
  • Avoid Date.now(): Date.now() measures integer milliseconds and is tied to wall-clock time rather than monotonic elapsed intervals.

2. Benchmarking Asynchronous Functions and Node.js Nanosecond Precision

For async functions or Promise-returning workloads, measure await fn(i) inside each sample iteration (noting that async timings include microtask/event-loop scheduling), and in Node.js use process.hrtime.bigint() when you need nanosecond-scale precision without floating-point drift:

// Benchmark an async function and return average/median milliseconds per call
async function benchmarkAsync(asyncFn, { iterations = 100, warmup = 10 } = {}) {
  if (typeof asyncFn !== "function") {
    throw new TypeError("Expected asyncFn to be a function.");
  }
  if (!Number.isInteger(iterations) || iterations <= 0 || !Number.isInteger(warmup) || warmup < 0) {
    throw new RangeError("Expected positive integer iterations and non-negative integer warmup.");
  }

  let sink;

  for (let i = 0; i < warmup; i += 1) {
    sink = await asyncFn(i);
  }

  const durationsMs = new Array(iterations);
  for (let i = 0; i < iterations; i += 1) {
    const start = performance.now();
    sink = await asyncFn(i);
    const end = performance.now();
    durationsMs[i] = end - start;
  }

  const sorted = [...durationsMs].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  const medianMs =
    sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];

  return {
    iterations,
    medianMs,
    minMs: sorted[0],
    maxMs: sorted[sorted.length - 1],
    _sink: sink
  };
}

// Node.js nanosecond helper using process.hrtime.bigint()
function measureNodeNanoseconds(fn) {
  if (typeof process === "undefined" || typeof process.hrtime?.bigint !== "function") {
    throw new Error("process.hrtime.bigint() is only available in Node.js.");
  }
  if (typeof fn !== "function") {
    throw new TypeError("Expected fn to be a function.");
  }

  const startNs = process.hrtime.bigint();
  const result = fn();
  const elapsedNs = process.hrtime.bigint() - startNs;

  return {
    elapsedNs,
    elapsedMs: Number(elapsedNs) / 1_000_000,
    result
  };
}

// Example usage:
// benchmarkAsync(async (n) => n * 2, { iterations: 50, warmup: 5 }).then(console.log);
  • Distinguish compute time from I/O or event-loop wait: Async measurements capture Promise resolution and scheduled callbacks, not just CPU instructions.
  • Convert bigint nanoseconds safely: Divide Number(elapsedNs) by 1_000_000 only when magnitudes fit safely within Number.MAX_SAFE_INTEGER.

3. Avoiding Common Benchmarking Pitfalls

Micro-benchmarks are easy to misread—guard against input mutation across iterations, polymorphic type shifts, browser DevTools throttling, and synthetic vs. real-world data mismatches:

// Compare two implementations fairly on fresh/unmutated inputs each iteration
function compareImplementations(candidates, createInput, options = {}) {
  if (!Array.isArray(candidates) || candidates.length === 0 || typeof createInput !== "function") {
    throw new TypeError("Expected non-empty candidates array and a createInput factory function.");
  }

  return candidates.map(({ name, fn }) => {
    if (typeof name !== "string" || typeof fn !== "function") {
      throw new TypeError("Each candidate must include a string name and function fn.");
    }

    const stats = benchmarkSync(() => {
      const freshInput = createInput();
      return fn(freshInput);
    }, options);

    return {
      name,
      medianMs: stats.medianMs,
      p95Ms: stats.p95Ms,
      minMs: stats.minMs
    };
  });
}

// Example usage comparing .sort() on a fresh copy vs. toSorted()
const results = compareImplementations(
  [
    { name: "slice+sort", fn: (arr) => [...arr].sort((a, b) => a - b) },
    { name: "toSorted", fn: (arr) => arr.toSorted((a, b) => a - b) }
  ],
  () => [42, 7, 19, 3, 88, 12],
  { iterations: 300, warmup: 30 }
);
console.table(results);
  • Reset mutating inputs outside timing or via factory: If a candidate sorts or mutates an array in place, sorting an already-sorted array on iteration 2 measures a different workload.
  • Test realistic sizes and disable CPU/network throttling: Small arrays (length < 10) often behave differently than production datasets, and DevTools CPU throttling skews timing numbers.