Measurement of Node.js execution time


In this post, I am sharing how to accurately measure code execution time in Node.js.

Measurement with Date

Many developers use JavaScript Date class in order to measure execution time. The following example illustrates this approach. I use setTimeout JavaScript function to simulate code running for about 1 second and use Date to measure its execution time. Variable start is assigned the test function start time and variable end is assigned the test function execution end time. The difference between these two variables is the test function execution time in milliseconds.

var start = new Date()
var simulateTime = 1000

setTimeout(function(argument) {
  // execution time simulated with setTimeout function
  var end = new Date() - start
  console.info('Execution time: %dms', end)
}, simulateTime)

And the output is like:

Execution time: 1002ms

The approach with JavaScript Date class is very popular, especially it can be used in any JavaScript program (including browsers). However, it has several disadvantages such as limitation to milliseconds (hard to measure functions executing a fraction of a millisecond) or vulnerability to clock drifts.

Measurement with process.hrtime()

Node.js has a more powerful mechanism to measure code execution time. It is process.hrtime() function, which returns high-resolution real time in [seconds, nanoseconds] array. The time 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 measurement with Date is better accurateness of measures. It is very important, especially when measuring executions, which last less than a millisecond.

In order to measure code execution time you have to provide time returned by the first process.hrtime() call, as a parameter to the second process.hrtime() call.

Let’s check the following example. As in the previous example, I use setTimeout function to simulate code running for 5 millisecond.

var start = new Date()
var hrstart = process.hrtime()
var simulateTime = 5

setTimeout(function(argument) {
  // execution time simulated with setTimeout function
  var end = new Date() - start,
    hrend = process.hrtime(hrstart)

  console.info('Execution time: %dms', end)
  console.info('Execution time (hr): %ds %dms', hrend[0], hrend[1] / 1000000)
}, simulateTime)

A few execution outputs:

Execution time: 7ms
Execution time (hr): 0s 6.858948ms

Execution time: 6ms
Execution time (hr): 0s 6.285195ms

Happy Coding!


Tags:

#date #interval #javascript #node.js #performance #time


You may also be interested in:



comments powered by Disqus