Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 321
Julius A Avatar asked Nov 24 '08 11:11

Julius A


People also ask

How do you find time taken by a function?

To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.

How do you measure run time?

To calculate the running time, find the maximum number of nested loops that go through a significant portion of the input. Some algorithms use nested loops where the outer loop goes through an input n while the inner loop goes through a different input m. The time complexity in such cases is O(nm).

How do you find the time taken to execute a program in C++?

clock() : clock() returns the number of clock ticks elapsed since the program was launched. Prototype / Syntax : clock_t clock(void); Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.


2 Answers

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:

  • MDN documentation
  • Node.js documentation
like image 171
vsync Avatar answered Sep 28 '22 04:09

vsync


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); 
like image 20
Owen Avatar answered Sep 28 '22 05:09

Owen