2011-01-24 13 views

答えて

38

EDIT: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); 

あなたのコードをプロファイリングしようとしている場合は、あなたがしたいことJavaScriptのプロファイラを含んFirebug拡張子を、してみてくださいそれはプロファイリングのための優れたユーザーインターフェースを持っていますが、それもその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. 
+2

'getTime()'を呼び出す必要はありません。 '-'演算子を使うと、各' Date'オブジェクトは時間値に変換されます。例えば、 'return new Date() - start;' –

+0

nice、私はスクリプトを変更しました。ありがとう:) – arnaud576875

+0

時にはソリューションがどれほど時にはソーシャルシンプルでエレガントなのか驚かされます! :-) – dotslash

8

new Date()の代わりにperformance.now()を使用してください。これにより、より正確でより良い結果が得られます。ここでは、この答えhttps://stackoverflow.com/a/15641427/730000

0

を参照してください

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 
関連する問題