Home >Web Front-end >JS Tutorial >How Can I Accurately Measure Function Execution Time in JavaScript?
Measuring the time taken by a function to execute is a crucial aspect of performance optimization. This question explores various methods to achieve accurate measurements, showcasing the evolution of performance APIs over time.
Modern browsers and Node.js provide the performance.now() API, which is now the standard for measuring execution time. This API returns a high-resolution timestamp representing the elapsed time since an arbitrary point in the past.
var startTime = performance.now(); doSomething(); // Measured code var endTime = performance.now(); console.log(`Call to doSomething took ${endTime - startTime} milliseconds`);
For measuring execution time in a more user-friendly manner, the console.time() and console.timeEnd() methods can be used. These methods automatically output the elapsed time to the console.
console.time('doSomething'); doSomething(); // Measured function console.timeEnd('doSomething');
It's important to note that the string passed to console.time() and console.timeEnd() must match to stop the timer correctly.
Over the years, the preferred method for measuring execution time has evolved:
The above is the detailed content of How Can I Accurately Measure Function Execution Time in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!