Timing Code Accurately
The most common approach to time a function or a segment of code is to repeat it many times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. However, this approach disregards the overhead of the loop. This can be remedied with a slight modification to the loop.
Illustrating the problem with JavaScript (although this method applies to all languages):
var start = new Date(); // Get current time
for (var i = 0; i < n; i++) {
myFunction();
}
var finish = new Date(): // Get current time
var ntimes = finish - start; // Elapsed time for n iterations
var once = ntimes / n; // Average time for one function call
This doesn’t really measure just how much time n calls to myFunction took. What we actually end up measuring is not just the time to execute one call to myFunction but also the overhead of one iteration:
// function + overhead var ntimes = finish - start; // Elapsed time for n iterations var once = ntimes / n; // Average time for one function call + iteration
Here’s a simple deviation from this approach to easily discount the loop overhead from the final measurement:
var start = new Date(); // Get current time
for (var i = 0; i < n; i++) {
myFunction();
}
var lap = new Date(): // Get current time
for (var i = 0; i < n; i++) {
myFunction();
myFunction(); // Call the function again
}
var finish = new Date(): // Get current time
// function + overhead
var elapsed1 = lap - start; // Elapsed time for n iterations
// function + function + overhead
var elapsed2 = finish - lap; // Elapsed time for n x 2 iterations
// function + function + overhead - (function + overhead)
// = function + function + overhead - function - overhead
// = function
var ntimes = elapsed2 - elapsed1; // Elapsed time for n iterations
var once = ntimes / n; // Average time for one function call