Node.js process.hrtime( ) Method
Last Updated :
03 Apr, 2023
The process.hrtime() method to measure code execution time which returns an array that includes current high-resolution real-time in [seconds, nanoseconds]. We measure the code execution time by providing the time returned by the first process.hrtime() call as a parameter in the second process.hrtime() call.
The Advantage of process.hrtime() is it measures time very accurately execution time which lasts less than a millisecond.
Syntax:
process.hrtime([time])
Parameter: This method accepts a single parameter as mentioned above and described below.
- time : The time is an optional parameter that must be the result of a previous process.hrtime() call to difference with the current time.
Return Type: It returns an array of 2 ints. The 1. int contains the seconds and the 2. int the nanoseconds. These times are relative to an arbitrary time in the past, and not related to the time of day.
Example 1:
Javascript
const hrTime = process.hrtime()
console.log( "Time in millisecond is: " , hrTime[0] * 1000 + hrTime[1] / 1000000)
|
Output:
Time in millisecond is: 218394926745.5
Example 2:
Javascript
const start_time = process.hrtime();
console.log( "Start Time:" , start_time);
setTimeout( function () {
const a = '40' ,
b = '50' ;
console.log( "Add of two number is :" , (a - 0) + (b - 0));
let end_time = process.hrtime(start_time);
console.log( "End Time:" , end_time);
}, 1000);
|
Output: It means 1 second and 8779100 nanoseconds from start to end time is taken.
Start Time: [ 682340, 452477300 ]
Add of two number is : 90
End Time: [ 1, 8779100 ]
Example 3:
Javascript
const start_time = process.hrtime();
console.log( "Start Time:" , start_time);
setTimeout( function () {
console.log( "Execution time will be calculated" +
" for printing this message...." );
let end_time = process.hrtime(start_time);
console.log( "End Time:" , end_time);
}, 1000);
|
Output: It means 1 second and 10987200 nanoseconds from start to end time is taken.
Start Time: [ 682865, 516565300 ]
Execution time will be calculated for printing this message....
End Time: [ 1, 10987200 ]
Reference: https://nodejs.org/api/process.html#process_process_hrtime_time
Share your thoughts in the comments
Please Login to comment...