How to measure time taken by a function to execute
I need to get execution time in milliseconds.
I originally asked this question back in 2008. The accepted answer then was to use
new Date().getTime()
However, we can all agree now that using the standardperformance.now()
API is more appropriate. I am therefore changing the accepted answer to this one.
Solution 1:
Using performance.now():
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`)
In
Node.js
it is required to import theperformance
class
importing performance
const { performance } = require('perf_hooks');
Using console.time: (living standard)
console.time('doSomething')
doSomething() // <---- The function you're measuring time for
console.timeEnd('doSomething')
Note:
The string being passed to the time()
and timeEnd()
methods must match
(for the timer to finish as expected).
console.time()
documentations:
- MDN documentation
- Node.js documentation
Solution 2:
use new Date().getTime()
The getTime() method returns the number of milliseconds since midnight of January 1, 1970.
ex.
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// do something
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);