Node.js console.time() Method
Last Updated :
13 Oct, 2021
The console.time() method is the console class of Node.js. It is used to starts a timer that is used to compute the time taken by a piece of code or function. The method console.timeEnd() is used to stop the timer and output the elapsed time in milliseconds to stdout. The timer can be accurate to the sub-millisecond.
Syntax
console.time( label )
Parameter: This method accepts a single parameter label that can be passed in the method as a parameter and if the label is not passed default label is automatically given to the method. The label can different for different functions or pieces of code.
Below examples illustrate the working of console.time() method in Node.js:
Example 1:
function addCount() {
var sum = 0;
for ( var i = 1; i < 100000; i++) {
sum += i;
}
return sum;
}
console.time();
addCount();
console.timeEnd();
|
Output:
default: 8.760ms
Example 2:
function addCount() {
var sum = 0;
for ( var i = 1; i < 100000; i++) {
sum += i;
}
return sum;
}
var timetaken = "Time taken by addCount function" ;
console.time(timetaken);
addCount();
console.timeEnd(timetaken);
|
Output:
Time taken by addCount function: 7.380ms
Example 3: This example using the different label for different functions simultaneously.
function addCount() {
var sum = 0;
for ( var i = 1; i < 100000; i++) {
sum += i;
}
return sum;
}
function countTime() {
var timetaken = "Time taken by addCount function" ;
console.time(timetaken);
console.log(addCount());
console.timeEnd(timetaken);
}
var label2 = "Time taken by countTime function" ;
console.time(label2);
countTime();
console.timeEnd(label2);
|
Output:
4999950000
Time taken by addCount function: 24.884ms
Time taken by countTime function: 25.928ms
Reference: https://nodejs.org/docs/latest-v11.x/api/console.html#console_console_time_label
Share your thoughts in the comments
Please Login to comment...