Open In App

Measure the Duration of Async Operations in Node.js

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Measuring the duration of asynchronous operations in Node.js can be critical for performance monitoring, debugging, and optimization. There are various techniques to achieve this, ranging from simple timing functions to using dedicated performance monitoring tools.

Syntax:

const calcTime = async () => {
const start = Date.now();
await someAsyncOperation();
const end = Date.now()
const duration = end - start;
}

Below are the approaches to measure the duration of async operations

Using console.time() and console.timeEnd()

The console.time() and console.timeEnd() methods are straightforward ways to measure the time taken by asynchronous operations. They are useful for quick debugging and basic performance checks.

console.time('fetchData');

const fetchData = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
};

fetchData().then(result => {
console.timeEnd('fetchData'); // Outputs: fetchData: 2001.234ms
console.log(result);
});

In this example, console.time() starts a timer labeled fetchData, and console.timeEnd() stops the timer and logs the duration to the console.

Using Date Objects

Using Date objects allows you to calculate the time difference between the start and end of an asynchronous operation.

const start = new Date();

const fetchData = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
};

fetchData().then(result => {
const end = new Date();
const duration = end - start;
console.log(`Duration: ${duration}ms`); // Outputs: Duration: 2000ms
console.log(result);
});

Here, the difference between the end time and the start time gives the duration of the operation.

Using process.hrtime()

The process.hrtime() function provides high-resolution real time in nanoseconds. It’s useful for more accurate timing measurements.

const start = process.hrtime();

const fetchData = async () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
};

fetchData().then(result => {
const end = process.hrtime(start);
const duration = end[0] * 1000 + end[1] / 1e6; // Convert to milliseconds
console.log(`Duration: ${duration}ms`); // Outputs: Duration: 2000.123ms
console.log(result);
});

process.hrtime() returns an array [seconds, nanoseconds], which provides high-resolution timing.

Steps to Setup Project

Step 1: Make a folder structure for the project.

mkdir myapp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Project Structure:

Screenshot-2024-07-01-225555

In the code example mentioned below, we have simulated an asynchronous operation using setTimeout() method. We perform the addition operation inside an async function that returns a promise. This promise is resolved with the result of addition after 2 seconds. Finally, we calculate and display the time taken to perform the addition operation inside our IIFE (Immediately Invoked Function Expression).

Node
// app.js

const asyncAdd = async (a, b) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(a + b);
    }, 2000);
  });
};

(async() => {
  const startTime = Date.now();
  const res = await asyncAdd(5, 2);
  const endTime = Date.now();

  const timeTaken = endTime - startTime;

  console.log(`Result of addition = ${res}`);
  console.log(`Time taken to perform addition =
          ${timeTaken} milliseconds`);
})();

Step to run the application: We can execute our app.js file using the following command on the command line.

node app.js

Output:



Next Article

Similar Reads