Measure the Duration of Async Operations in Node.js
Last Updated :
10 Jul, 2024
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:

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:
Similar Reads
How to handle asynchronous operations in Node ?
NodeJS, renowned for its asynchronous and event-driven architecture, offers powerful mechanisms for handling asynchronous operations efficiently. Understanding how to manage asynchronous operations is crucial for NodeJS developers to build responsive and scalable applications. What are Asynchronous
2 min read
Asynchronous Patterns in Node.js
Asynchronous programming in NodeJS allows tasks to run in the background without blocking execution, enabling efficient handling of multiple operations. It uses the event loop, callbacks, promises, and async/await to manage non-blocking I/O tasks seamlessly. Understanding Asynchronous ProgrammingAsy
5 min read
Describe the use of Timer methods in Node.js
In this article, we are going to explore timers in Node.js and how to use them in various scenarios. The timers method in node.js contains different types of functions that are used for executing a block of code or a function at a specific period of time. It is a global module that is not required t
3 min read
Moment.js moment.duration().days() Method
The moment().duration().days() method is used to get the days of the duration. This number of days is calculated as a subset of a month, therefore having a value between 0 and 30. The length of days for calculating each month is 31 days. Syntax: moment().duration().days(); Parameters: This method do
2 min read
Node.js util.types.isAsyncFunction() Method
The util.types.isAsyncFunction() method is an inbuilt application programming interface of the util module which is used to type check for asynchronous functions in the node.js. Syntax:Â util.types.isAsyncFunction( value ) Parameters: This method accepts a single parameter as mentioned above and des
2 min read
Moment.js moment.duration().as(String) Method
The moment().duration().as() Method returns the specified unit of time from the duration object. It is basically an alternative to other functions like asWeeks(), asMonths(), etc. It also supports all shorthand keys from the moment.add() method. Syntax: moment().duration().as(String); Parameters: Th
2 min read
Explain the Mechanism of event loop in Node.js
JavaScript is a single-threaded, non-blocking, asynchronous language that uses the concept of event loop to make it work asynchronously even if it is single-threaded. Feature: The Event Loop is responsible for sending functions from the event queue to the Stack for processing when it becomes empty.
2 min read
Moment.js moment.duration().months() Method
The moment().duration().months() method is used to get the month of the duration. This method returns a value between 0 and 11. This method is different from the asMonths() method which returns the length of the given duration in months. Syntax: moment().duration().months(); Parameters: This method
2 min read
Moment.js moment.duration().add() Method
The moment().duration().add() method is used to add a given time to the duration. The time to be added can be another Duration object, value in milliseconds, or a representation of the time using a string and numerical value. All the shorthands and keys used for creating durations can be used here f
4 min read
Explain the Process Object in Node.js
In this article, we are going to explore about process object of Node.js in detail. The Process object in node.js is a global object that can be used in any module without requiring it in the environment. This object is useful in the perspective of getting the information related to the node.js envi
3 min read