Javascript – 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 standard API is more appropriate. I am therefore changing the accepted answer to this one.

Best Solution


var startTime =

doSomething()   // <---- measured code goes between startTime and endTime
var endTime =

console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)

In Node.js it is required to import the performance class

importing performance

const { performance } = require('perf_hooks');

Using console.time: (living standard)

doSomething()   // <---- The function you're measuring time for 

The string being passed to the time() and timeEnd() methods must match
(for the timer to finish as expected).

console.time() documentations: