[Solved-6 Solutions] How to measure time taken by a function to execute - javascript tutorial



Problem:

How to measure time taken by a function to execute ?

Solution 1:

You can try this :

var measure = require('measure');  
var collectTime = measure.measure('timer1');
// measure first time
collectTime();  
setTimeout(function() {  
    // measure second time
    collectTime();
}, 100);
setTimeout(function() {  
    // measure third time
    collectTime();
    console.log(measure.stats('timer1'));
}, 1000);

Output:

[~/]$ node measureTime.js
{ ct: 3, total: 1105, max: 1002, min: 0 }

Solution 2:

We can use console.time: (non-standard)

console.time('someFunction');

someFunction(); // run whatever needs to be timed in between the statements

console.timeEnd('someFunction');

We could use the standard performance.now() API:

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

Solution 3:

Use new Date().getTime(). The getTime() method returns the number of milliseconds.

var start = new Date().getTime();

for (we = 0; we < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

Solution 4:

To get precise values we should use Performance interface . It's supported in modern versions of Firefox, Chrome , Opera and IE.

var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")

Solution 5:

Use add operator:

 var start = +new Date()

 for (i = 0; i < 50000; ++i) {
   // do something
  }

 var end = +new Date()
 var time = end - start;
 console.log('total execution time = '+ time + 'ms');

Solution 6:

process.hrtime() is available within Node.js - It returns a value in nanoseconds.

var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)


Related Searches to javascript tutorial - How to measure time taken by a function to execute