Measure execution time of a method in JavaScript
This post will discuss how to measure the execution time of a method in JavaScript.
1. Using performance.now() function
The performance.now() method returns the time elapsed since the time origin, measured in milliseconds. It returns timestamp up to microsecond precision.
The following example demonstrates the usage of the performance.now() method to track the execution time of an operation.
|
1 2 3 4 5 6 7 8 9 10 11 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var start = window.performance.now(); // task starts for (var i = 0; i < 100000000;i++); // task ends var end = window.performance.now(); console.log(`Execution time: ${end - start} ms`); |
Alternatively, you can use the performance.now() method from Performance Timing API, which is the same as implemented in modern Web browsers.
|
1 2 3 4 5 6 7 8 9 10 |
const {performance} = require('perf_hooks'); var start = performance.now(); // task starts for (var i = 0; i < 100000000;i++); // task ends var end = performance.now(); console.log(`Execution time: ${end - start} ms`); |
2. Using Console.time() function
The console.timeEnd() method starts a timer with the specified label. A subsequent call to the console.timeEnd() method with the same label will output milliseconds elapsed since the first call was made.
|
1 2 3 4 5 6 7 |
console.time('Execution Time'); // task starts for (var i = 0; i < 100000000;i++); // task ends console.timeEnd('Execution Time'); |
3. Using Date Object
Another plausible way to track how long an operation took is to use the Date.now() method, which returns the total number of milliseconds elapsed since the Unix Epoch. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
var start = Date.now(); // task starts for (var i = 0; i < 100000000;i++); // task ends var end = Date.now(); console.log(`Execution time: ${end - start} ms`); |
Alternatively, you can use the unary plus operator to convert the date returned by the Date constructor into milliseconds.
|
1 2 3 4 5 6 7 8 |
var start = +new Date(); // task starts for (var i = 0; i < 100000000;i++); // task ends var end = +new Date(); console.log(`Execution time: ${end - start} ms`); |
That’s all about measuring the execution time of a method in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)