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.
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.
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`);work took 1.84 msYour 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.