Pete D
Pete D

Reputation: 837

Is using the Date object to count the speed of the Javascript execution correct?

Is it a correct way to count the speed of a specific code using the Date object?

var start = +new Date(); //get start time

    /*
     *    
     *    all the commands here
     *
     */

var stop = +new Date(); //get stop time
console.log(stop - start);

Or is there another preferable way to get results. I guess this way is very influanced by which browser you test it on and so forth...

Upvotes: 0

Views: 271

Answers (4)

Esailija
Esailija

Reputation: 140230

Well generally yes, if you are doing painting, you can factor in a rough painting time as well with:

var start = +new Date();

//Do dom methods draw to canvas etc

setTimeout( function() {
   var stop = +new Date();
   console.log( stop - start - 13 );
}, 13 );

Also, make sure you call each test as a function and warm-up the functions before timing them instead of doing the code in-line.

function test1() {
    //ops
}

function test2() {
    //ops
}
var l = 1e5;
while (l--) {
    //warmup
    test1();
    test2();
}
var start = +new Date();
var l = 1e5;

while (l--) {
    test1();
}

var stop = +new Date();
console.log(stop - start);


var start = +new Date();
var l = 1e5;

while (l--) {
    test2();
}

var stop = +new Date();
console.log(stop - start);

You should note that this setup invites JIT optimizations (which is why it was done in the first place) so you should look out for dead code elimination.

Upvotes: 3

Emmanuel Capelle
Emmanuel Capelle

Reputation: 44

Here's an alternative solution if you use Firefox: you can use the profiler to know the exact time it takes for your javascript to run.

How to use it (the fast way):
1) Bring up the profiler by hitting shift-f5 in firefox.
2) Start profiling and reload your web page
3) Stop profiling, it should then load the profiling data
4) expand the little arrow looking like : "> (total)", it will show up all the scripts that have been run during the page load, sorted by execution time (in ms)
5) Find your script, the time is on the left side of the tool, and expressed in MS.

Upvotes: 1

Ezequiel Gorbatik
Ezequiel Gorbatik

Reputation: 2585

Yes there is a better way, check this What is the best way to profile javascript execution?

Basically:

console.profile([title])
...
console.trace()
...
console.profileEnd ()

Upvotes: 1

Wolfgang Kuehn
Wolfgang Kuehn

Reputation: 12926

Better use the console timer: https://developer.mozilla.org/en-US/docs/Web/API/console

console.time("answer time");
alert("Click to continue");
console.timeEnd("answer time");

Upvotes: 2

Related Questions