How to measure time taken by a function to execute

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 the performance 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:

Leave a Comment