【发布时间】:2011-06-14 15:50:07
【问题描述】:
如何测量脚本从开始到结束运行所需的时间?
start-timing
//CODE
end-timing
【问题讨论】:
-
请记住,语法正确的标题和相关标签会产生重大影响。
标签: javascript timer
如何测量脚本从开始到结束运行所需的时间?
start-timing
//CODE
end-timing
【问题讨论】:
标签: javascript timer
例如:
在JS文件的开头写:performance.mark("start-script")
在JS文件的结尾写:performance.mark("end-script")
那么你也可以测量它:
performance.measure("total-script-execution-time", "start-script", "end-script");
这将为您提供运行整个脚本执行所需的时间。
【讨论】:
这是一个像秒表一样工作的快速功能
var Timer = function(id){
var self = this;
self.id = id;
var _times = [];
self.start = function(){
var time = performance.now();
console.log('[' + id + '] Start');
_times.push(time);
}
self.lap = function(time){
time = time ? time: performance.now();
console.log('[' + id + '] Lap ' + time - _times[_times.length - 1]);
_times.push(time);
}
self.stop = function(){
var time = performance.now();
if(_times.length > 1){
self.lap(time);
}
console.log('[' + id + '] Stop ' + (time - _times[0]));
_times = [];
}
}
// called with
var timer = new Timer('process label');
timer.start(); // logs => '[process label] Start'
// ... code ...
timer.lap(); // logs => '[process label] Lap ' + lap_time
// ... code ...
timer.stop(); // logs => '[process label] Stop ' + start_stop_diff
【讨论】:
编辑:在 2011 年 1 月,这是最好的解决方案。现在应该首选其他解决方案(例如performance.now()。
var start = new Date();
// CODE
var time = new Date() - start;
// time is the number of milliseconds it taken to execute the script
您可能还想将其包装在一个函数中:
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 分析器。它具有出色的分析用户界面,但也可以通过其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.
【讨论】:
getTime():使用- 运算符将每个Date 对象转换为其时间值。例如,return new Date() - start;
performance.now() 应该优先于 new Date() - 请参阅 Morteza Ziaeemehr 的其他答案。
使用performance.now() 而不是new Date()。这提供了更准确和更好的结果。看到这个答案https://stackoverflow.com/a/15641427/730000
【讨论】: