In this post I will share how to measure execution time easily in Node.js.

Many developers use JavaScript Date class in order to measure execution time. In the following example I will use setTimeout in order to simulate execution time.

var start = new Date();

setTimeout(function (argument) {
    // execution time simulated with setTimeout function
    var end = new Date() - start;"Execution time: %dms", end);
}, 1000);

And the output is like:

Execution time: 1002ms

Variable end is set a number of milliseconds which elapsed between setting start and end variables.

This approach is very popular, especially it can be used in any JavaScript program. Node.js, however, has more powerful mechanism to measure performance between intervals. It is process.hrtime() function which returns high-resolution real time in [seconds, nanoseconds] Array. The time Array is relative to an arbitrary time in the past (not related to the time of day) and therefore not subject to clock drifts.

Another advantage of process.hrtime() over the Date approach is better accurateness of measured intervals which is very important especially while measuring intervals which last less than a millisecond.

Node that the second time tuple Array component is a number of nanoseconds and it has to be divided by 1,000,000 in order to get time in milliseconds.

In order to measure performance interval you have to provide time returned by first process.hrtime() call as a parameter to the second process.hrtime() call. Let's check the following example:

var start = new Date();
var hrstart = process.hrtime();

setTimeout(function (argument) {
    // execution time simulated with setTimeout function
    var end = new Date() - start,
        hrend = process.hrtime(hrstart);"Execution time: %dms", end);"Execution time (hr): %ds %dms", hrend[0], hrend[1]/1000000);
}, 1);

A few execution outputs:

Execution time: 1ms
Execution time (hr): 0s 1.025075ms

Execution time: 3ms
Execution time (hr): 0s 2.875302ms