如何衡量脚本的执行时间? [英] How can I measure the execution time of a script?
本文介绍了如何衡量脚本的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何衡量脚本从头到尾运行所需的时间?
How would I measure the time it takes for a script to run from start to finish?
start-timing
//CODE
end-timing
推荐答案
编辑:2011年1月,这是最好的解决方案。其他解决方案(例如 performance.now()
现在应该是首选。
EDIT: in January 2011, this was the best available solution. Other solutions (such as performance.now()
should be preferred now.
var start = new Date();
// CODE
var time = new Date() - start;
// time is the number of milliseconds it taken to execute the script
您可能还想将其包装在函数中:
You may also want to wrap that in a function:
function time_my_script(script) {
var start = new Date();
script();
return new Date() - start;
}
// call it like this:
time = time_my_script(function() {
// CODE
});
// or just like this:
time = time_my_script(func);
如果您要对自己的代码进行分析,可能需要尝试 Firebug 扩展程序,其中包括一个javascript profiler。它有一个很好的用户界面进行性能分析,但它也可以用 console api :
If you are trying to profile your code, you may want to try the Firebug extension, which includes a javascript profiler. It has a great user interface for profiling, but it also can be done programmatically with its console api :
console.time('timer1');
// CODE
console.timeEnd('timer1'); // this prints times on the console
console.profile('profile1');
// CODE
console.profileEnd('profile1'); // this prints usual profiling informations, per function, etc.
这篇关于如何衡量脚本的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文