Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to measure how long code takes

Short answer

performance.now() returns the time in milliseconds with fractions. Subtract the start from the end:

const start = performance.now();
 
let sum = 0;
for (let i = 0; i < 1_000_000; i++) sum += i;
 
const ms = performance.now() - start;
console.log(typeof ms, ms >= 0);

Output:

number true

Async operations

For a request or a timer, take the second measurement after await:

const start = performance.now();
await new Promise((resolve) => setTimeout(resolve, 200));
const ms = Math.round(performance.now() - start);
 
console.log(ms >= 195 ? 'about 200 ms' : ms);

Output:

about 200 ms

console.time

In the browser console and in Node.js, console.time() and console.timeEnd() print the time themselves:

console.time('sorting');
const numbers = Array.from({ length: 100000 }, () => Math.random()).sort();
console.timeEnd('sorting');

Output:

sorting: 42.7 ms

Common mistake

A single measurement is unreliable: the first run is often slower. Repeat the code many times and compare averages.

const measure = (fn, times = 100) => {
  const start = performance.now();
  for (let i = 0; i < times; i++) fn();
  return (performance.now() - start) / times;
};
 
const average = measure(() => [3, 1, 2].sort());
console.log(average < 1 ? 'less than 1 ms per run' : 'slow');

Output:

less than 1 ms per run

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.