簡體   English   中英

如何衡量腳本的執行時間?

[英]How can I measure the execution time of a script?

我如何衡量腳本從頭到尾運行所需的時間?

 start-timing
   //CODE
 end-timing

編輯 :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探查器。 它有一個很好的用戶界面進行性能分析,但它也可以通過其控制台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.

使用performance.now()而不是new Date() 這提供了更准確和更好的結果。 請參閱此答案https://stackoverflow.com/a/15641427/730000

這是一個像秒表一樣工作的快速功能

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

使用用戶時間api

例如:在JS文件的開頭寫: performance.mark("start-script")

在JS文件的末尾寫: performance.mark("end-script")

那么你也可以測量它:

performance.measure("total-script-execution-time", "start-script", "end-script");

這將為您提供運行整個腳本執行所需的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM