Node.js console.time() Method
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:
// Node.js program to demonstrate the // console.time() method // Sample function function addCount() { // Variable declaration var sum = 0; for ( var i = 1; i < 100000; i++) { // Adding i to the sum variable sum += i; } // Return sum value return sum; } // Starts the timer console.time(); // Function call addCount(); // Ends the timer and print the time // taken by the piece of code console.timeEnd(); |
Output:
default: 8.760ms
Example 2:
// Node.js program to demonstrate the // console.time() method // Sample function function addCount() { // Variable declaration var sum = 0; for ( var i = 1; i < 100000; i++) { // Adding i to the sum variable sum += i; } return sum; // returning sum } var timetaken = "Time taken by addCount function" ; // Starts the timer. The label value is timetaken console.time(timetaken); addCount(); // function call // Ends the timer and print the time // taken by the piece of code console.timeEnd(timetaken); |
Output:
Time taken by addCount function: 7.380ms
Example 3: This example using the different label for different functions simultaneously.
// Node.js program to demonstrate the // console.time() method // Sample function function addCount() { var sum = 0; // Variable declaration for ( var i = 1; i < 100000; i++) { sum += i; // Adding i to the sum variable } return sum; // returning sum } function countTime() { var timetaken = "Time taken by addCount function" ; // Starts the timer, the label value is timetaken console.time(timetaken); console.log(addCount()); // function call // Ends the timer and print the time // taken by the piece of code console.timeEnd(timetaken); } var label2 = "Time taken by countTime function" ; // Starts the timer, the label value is label2 console.time(label2); countTime(); // function call // Ends the timer and print the time // taken by the piece of code 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