Timing Code Accurately
October 19th, 2008The most common approach to time a function or a segment of code is to repeat it a lot of times in a loop, measure the time the entire loop takes and then divide that number with the number of iterations. Illustrating this 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
However, this doesn’t really measure just how much time n calls to myFunction took. There’s also the overhead of the loop itself. What we actually end up measuring is not just the time to execute one call to myFunction but also the overhead of one iteration: Read the rest of this entry »