HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to measure time taken by a function to execute

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctionmeasuretimetakenexecute

Problem

I need to get execution time in milliseconds.

Note: 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 performance.now() API is more appropriate. I am therefore changing the accepted answer to this one.

Solution

Using performance.now():
const startTime = performance.now()

doSomething() //

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() //

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

Context

Stack Overflow Q#313893, score: 2816

Revisions (0)

No revisions yet.