How to measure performance in JavaScript (Node or Browser)

08 October, 2019

Author: Max Rozen

How to measure performance in JavaScript (Node or Browser)

Some older advice on the internet will suggest you use Date.now() to measure the start and end of your process. It is generally advised that you don't do that any more. The two main issues with using Date.now() are that:

  • Date.now()'s minimum resolution is one millisecond
  • It's possible to change system time while you're monitoring performance, resulting in negative results

Instead, it is recommended to use performance.now(). performance.now() is a new(ish) browser-based API, and it's also available in Node since v8.5.0 (prior to v8.5.0 you could download a node package).

The advantages to using performance.now() are:

  • It's monotonic (time can only ever go forward), useful for when system time changes
  • It returns a double, with microseconds as a fraction

performance.now() Usage

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

Prior to performance.now() in Node, process.hrtime() was used. It returns an array of [seconds, nanoseconds], is also monotonic, and is higher resolution than Date.now().

To measure your code's execution time you need to pass in the time from the first process.hrtime() call as an argument to your second process.hrtime() call.

Using it was slightly annoying, as you had to divide the second number by 1000000 to return milliseconds.

process.hrtime() Usage

var t0 = process.hrtime();
doSomething();
var t1 = process.hrtime(t0);
console.log(`Call to doSomething took ${t1[0]} seconds, ${t1[1]/1000000} ms`);

There's also a whole bunch of syntactical sugar available for process.hrtime(), such as console.time(), and various npm packages.

In general, I recommend using performance.now() going forward, as it's standard between Browser and Node environments.

Enjoyed this post? Receive the next one in your inbox!