2011-01-24 5 views

답변

38

편집 : 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 확장 프로그램을 사용해보십시오. 프로파일 링을위한 훌륭한 사용자 인터페이스를 가지고 있지만 프로그래밍 방식으로 프로그래밍 할 수 있습니다. 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

스크립트를 변경해 주셔서 고마워요. :) – arnaud576875

+0

때로는 솔루션이 간단하고 우아한 sooooo입니다. :-) – dotslash

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 
관련 문제