How can I measure the execution time of a script?

2019-03-10 12:55发布

问题:

How would I measure the time it takes for a script to run from start to finish?

 start-timing
   //CODE
 end-timing

回答1:

EDIT: in January 2011, this was the best available solution. Other solutions (such as performance.now() should be preferred now.

var start = new Date();
    // CODE
var time = new Date() - start;
// time is the number of milliseconds it taken to execute the script

You may also want to wrap that in a function:

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

If you are trying to profile your code, you may want to try the Firebug extension, which includes a javascript profiler. It has a great user interface for profiling, but it also can be done programmatically with its 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:

Use performance.now() instead of new Date(). This provides a more accurate and better result. See this answer https://stackoverflow.com/a/15641427/730000



回答3:

Here is a quick function to work like a stopwatch

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


回答4:

Use the User Timing api

For example: in the beginning of the JS file write: performance.mark("start-script")

at the end of the JS file write: performance.mark("end-script")

then you can measure it too:

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

This will give you the time it takes to run the entire script execution.