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.
You can use console.time : (non-standard)
console.time('someFunction');
someFunction(); // run whatever needs to be timed in between the statements
console.timeEnd('someFunction');
Note :
The string being pass to the time()
and timeEnd()
methods must match
(for the timer to finish as expected).
Update
You could use the standard performance.now() API, like so:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
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);
Don't use Date(). Read below.
Use performance.now()
:
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
It works on:
IE 10 ++
FireFox 15 ++
Chrome 24 ++
Safari 8 ++
Opera 15 ++
Android 4.4 ++
etc, etc
console.time
may be viable for you , but it's non-standard §:
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Besides browser support, performance.now
seems to have the potential to provide more accurate timings as it appears to be the bare-bones version of console.time
.
<rant> Also, DON'T EVER use Date
for anything because it's affected by changes in "system time". Which means we will get invalid results —like "negative timing"— when the user doesn't have an accurate system time:
On Oct 2014, my system clock went haywire and guess what.... I opened Gmail and saw all of my day's emails "sent 0 minutes ago ". And I'd thought Gmail is supposed to be built by world-class engineers from Google.......
(Set your system clock to one year ago and go to Gmail so we can all have a good laugh. Perhaps someday we will have a Hall of Shame for JS Date
.)
Google Spreadsheet's now()
function also suffers from this problem.
The only time you'll be using Date
is when you want to show the user his system clock time. Not when you want to get the time or to measure anything.
上一篇: Javascript中的原型对象打破了jQuery?
下一篇: 如何测量一个函数执行所花费的时间