Measuring performance in JavaScript

Jan 9, 2017  

In order to measure the time taken to execute a piece of JavaScript, one of the solutions provided by both the browsers and node is to use console.time(label) and console.timeEnd(label), as explained on MDN.

1console.time ('perf');
2// ...do whatever takes time...
3console.timeEnd ('perf');

This will display a message to the console:

perf: 114.660ms

How can we get the time back?

The console API is great for just printing out the time taken by a piece of code, but it does not return the total elapsed time. In the browser, the Window.performance API provides a solution, but it is not available when executing tests inside node or Wallaby.js.

So let’s use process.hrtime in these cases:

1function clock (start) {
2  if (start) {
3    const end = process.hrtime (start);
4    return (end[0] * 1000) + (end[1] / 1000000);
5  } else {
6    return process.hrtime ();
7  }
8}

And here is how you’d use it:

1const perf = clock ();
2// ...
3const ms = clock (perf); // elapsed milliseconds

Asserting execution time with mai-chai

When using mai-chai, I can assert on the execution time by writing:

1import {clock} from 'mai-chai';
2
3const perf = clock ();
4// ...
5expect (clock (perf)).to.be.at.most (150);