martes, 24 de marzo de 2015

console.timing() - measure multiple calls of a code block

The following is an utility, similar to console.time / console.timeEnd to measure how long a code block takes to execute but it will take in account sevaral times and report the total calling time and average. Very useful wile profiling code blocks execution time.


console.timing = function(key)
{
 this.timings = this.timings || {}; 
 this.timings[key] = this.timings[key] || []; 
 this.timings[key].push(performance.now()); 
};

console.timingEnd = function(key)
{
 var t0 = this.timings[key][this.timings[key].length-1]; 
 this.timings[key][this.timings[key].length-1] = performance.now() - t0;
}; 

console.timingReport = function(key)
{
 var times = this.timings[key]; 
 var sum = 0;
 for (var i = 0; i < times.length; i++) 
 {
  sum += times[i]; 
 }
 var average = sum / times.length;
 console.log(key + ': times: ' + times.length + ', sum: ' + sum + ', average: ' + average);  
};

console.timingReset = function(key)
{
 this.timings[key] = []; 
}; 

No hay comentarios: