Skip to content
jshacks.dev
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Summarize in AI

To see how long something takes, subtract two timestamps. performance.now() is the right clock for it, and it is a global in browsers and in Node.js 16 and later.

timing.jsJavaScript
function work() {
  let total = 0;
  for (let i = 0; i < 1_000_000; i++) total += i;
  return total;
}

const start = performance.now();
work();
const elapsed = performance.now() - start;

console.log(`work took ${elapsed.toFixed(2)} ms`);
Text
work took 1.84 ms

Your number will differ with the machine and with how warm the code is. The value is milliseconds since the time origin, with a fractional part, and it is monotonic: it never goes backwards when the system clock is adjusted, which Date.now() can do after an NTP sync or a manual change.

Browsers round the value to limit timing attacks, so very short measurements are coarse there. Time one run only to get a rough idea; to compare approaches, repeat the work many times, as in the performance API docs.

Taggednode 24
Share

More snippets

Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read
Performance

Load third-party scripts after interaction

Inject a chat widget or analytics script only after the first scroll, click or key press, so it does not compete with your own code during page load.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.