Home >Web Front-end >JS Tutorial >How Can I Accurately Measure JavaScript Function Execution Time?
Measuring Execution Time of a Function with JavaScript
Determining the execution time of a function is a crucial task in performance optimization. In JavaScript, several approaches can be used to measure this time accurately.
Using performance.now()
The performance.now() API provides a high-resolution timestamp measured in milliseconds. The following syntax demonstrates how to use it:
const startTime = performance.now(); doSomething(); // Function to be measured const endTime = performance.now(); console.log(`Function call took ${endTime - startTime} milliseconds`);
Using console.time()
The console.time() and console.timeEnd() functions provide a convenient way to measure execution time. The syntax is as follows:
console.time('doSomething'); doSomething(); // Function to be measured console.timeEnd('doSomething');
Note that the string passed to console.time() must match the string passed to console.timeEnd() for proper time recording.
Additional Notes:
The above is the detailed content of How Can I Accurately Measure JavaScript Function Execution Time?. For more information, please follow other related articles on the PHP Chinese website!