Bao
Bao

Reputation: 607

How to calculate runtime speed in standalone javascript program?

I am doing some JavaScript exercise and thinking about ways to improve my solution(algorithm) to the exercise. I am thinking of calculating runtime speed after tweaking the code so I will know how much the speed is improved. I searched and found this method and think I can do the same. Here is what I did,

var d = new Date();
var startTime = d.getTime();
var endTime;

function testTargeAlgorithm(){
  ....
  ....
}

testTargetAlgorithm();

endTime = d.getTime();
console.log(endTime-startTime);

It's a very simple algorithm so I don't expect there will be notable difference between the time. But if millisecond cannot measure the speed improvement, what else can I do?

Upvotes: 3

Views: 4277

Answers (3)

deramko
deramko

Reputation: 2834

Run the same function again and again.

var startTime = (new Date()).getTime();
for(var i=0;i<1000;i++) {
    testTargeAlgorithm()
}
var endTime = (new Date()).getTime();
console.log(endTime-startTime);

edited to reflect suggestions, thanks Marcel

Upvotes: 2

Bao
Bao

Reputation: 607

I ended up using process.hrtime() to provide nanosecond precision for measuring runtime performance. Note this method only works with Node.js. In Chrome & Firefox, you can use performance.now().

Even running same algorithm/function, the returned time difference still varies (in nanosecond unit tho) presumably due to CPU usage and other unknown effects, so it is suggested to run a good number of times and calculate the average. For example:

function calAvgSpeed(timesToRun, targetAlgorithm){

var diffSum = 0;
for(var i = 1; i <= timesToRun; i++){
    var startTime = process.hrtime();
    targetAlgorithm();
    var diff = process.hrtime(startTime);
    diffSum += diff[1];
   }
   return Math.floor(diffSum / times);
}

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187252

You can use performance.now() if the engine supports it. This gives a time in milliseconds, with sub-millisecond precision, since the page loaded or app started.

performance.now() // 26742.766999999956

I know Chrome supports it, but not sure about other browsers, node.js, or other engines standalone js engines.


Or you can run your code many times in a loop, and measure the total time taken.

Upvotes: 4

Related Questions