Measuring Execution Time of a Function
Question:
How do I determine the execution time of a function in milliseconds?
Answer:
Using performance.now()
The performance.now() API provides a high-resolution timestamp representing the time since navigation start. To measure the execution time of a function, follow these steps:
var startTime = performance.now(); doSomething(); // <---- Measured code goes between startTime and endTime var endTime = performance.now(); console.log(`Call to doSomething took ${endTime - startTime} milliseconds`);
For Node.js, first import the performance class:
const { performance } = require('perf_hooks');
Using console.time
console.time provides a convenient way to measure execution time in the browser. Here's how to use it:
console.time('doSomething'); doSomething(); // <---- The function you're measuring time for console.timeEnd('doSomething');
Note: The string passed to console.time() and console.timeEnd() must match for the timer to end correctly.
References:
The above is the detailed content of How Can I Measure the Execution Time of a JavaScript Function in Milliseconds?. For more information, please follow other related articles on the PHP Chinese website!