Node.js

Measure a code interval with performance.now

Use performance.now for elapsed-time measurements inside one process. It supplies a monotonic high-resolution time reference rather than a wall-clock timestamp intended for calendar display.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {performance} from "node:perf_hooks";
const start = performance.now();
let total = 0;
for (let i = 0; i < 100000; i++) total += i;
const elapsed = performance.now() - start;
console.log(total);
console.log(Number.isFinite(elapsed) && elapsed >= 0);

How it works

Subtracting the starting measurement yields elapsed milliseconds. The loop’s result is printed so the work has an observable purpose. This helps with local diagnostics, but a single interval is only one sample under current process and machine conditions.

Limits and mistakes

Short timings are affected by compilation, scheduling, background load, and measurement overhead. They are not a trustworthy public benchmark by themselves. Warm up relevant code and collect a distribution when performance comparisons actually matter.

Check the result

Expect 4999950000 and true. Do not assert an exact duration; compare repeated observations under documented conditions if you need to investigate a regression.

Sources

Reference documentation for the behavior used in this guide: