Categories
JavaScript Answers

How to measure the execution time of Node.js code with callbacks?

Spread the love

Sometimes, we want to measure the execution time of Node.js code with callbacks.

In this article, we’ll look at how to measure the execution time of Node.js code with callbacks.

How to measure the execution time of Node.js code with callbacks?

To measure the execution time of Node.js code with callbacks, we can use the process.hrtime method.

For instance, we write

let start = process.hrtime();

const elapsedTime = (note) => {
  const precision = 3;
  const [startTime, endTime] = process.hrtime(start)
  const elapsed = endTime / 1000000;
  console.log(startTime, elapsed);
  start = process.hrtime();
}

to create the elaspedTime function tyat calls process.hrtime with start to return the timestamp of the elasped time and assign that to endTime.

The endTime is in nanoseconds.

So we divide endTime by 1000000 to get the elasped time in seconds.

Conclusion

To measure the execution time of Node.js code with callbacks, we can use the process.hrtime method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *