2011-01-24 2 views

ответ

38

EDIT: в январе 2011 года, это было лучшим выходом. Другие решения (например, 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

nice, я сменил скрипт, спасибо :) – 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