How to measure time taken by a function to execute
Posted By: Jangwenyi
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
Using performance.now():
var t0 = performance.now()
doSomething() // <---- The function you're measuring time for
var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
NodeJs
: it is required to import theperformance
class
Using console.time: (non-standard) (living standard)
console.time('someFunction')
someFunction() // Whatever is timed goes between the two "console.time"
console.timeEnd('someFunction')
Note:
The string being pass to the time()
and timeEnd()
methods must match
(for the timer to finish as expected).
console.time()
documentations:
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.