Measuring Execution Times in JavaScript with console.time()

Today, I want to show you debugging method, more specifically one for measuring execution times: Say hello to console.time().

Measuring Execution Times the Classic Way

Here's a small JavaScript snippet which concatenates the first one million natural numbers:
 var i, output = "";    
 for (i = 1; i <= 1e6; i++)  
   output += i;  

If you're wondering what 1e6 means, it's just a short way to write ten to the sixth power, which equals one million. It means exactly the same as the number literal 1000000.

The script is very simple, yet takes a couple dozen milliseconds (about 150ms on my machine) to execute. How did I measure this time? I could've done something like this:
 var i, output = "";  
 // Remember when we started  
 var start = new Date().getTime();  
 for (i = 1; i <= 1e6; i++)  
   output += i;  
 // Remember when we finished  
 var end = new Date().getTime();  
 // Now calculate and output the difference    
 console.log(end - start);  

This approach is very straightforward. It also has the advantage that it runs pretty much everywhere. If you're using a modern browser though, there's a shorthand method for measuring durations and logging them to the console. Let's inspect console.time()now.

Measuring Execution Times Using console.time()
Making use of console.time(), the code from before can be rewritten as this:

 var i, output = "";  
 // Start timing now  
 console.time("concatenation");  
 for (i = 1; i <= 1e6; i++)  
   output += i;  
 // ... and stop.  
 console.timeEnd("concatenation");  

We've now managed to make the code more expressive and slightly shorter than before: The call to console.time() starts a timer with the name concatenation, which is later stopped by console.timeEnd(). The timer names passed to both function calls have to match in order for the measuring to work.
Note that console.time() and console.timeEnd() are only supported by modern browsers, starting with Chrome 2, Firefox 10, Safari 4, and Internet Explorer 11.

Displaying the Measured Duration in the Console

Chrome 31 has written the following output to the console:

Here is what Firefox 25 gives us (notice the concatenation: timer started information):

A Closing Word on High-Precision Timing

If you need to measure time precisely, neither Date.getTime() nor console.time()will get you far. Check out John Resig's blog post about the accuracy of JavaScript time to learn why.
There's a different API for that purpose, though: the Performance interface, which is implemented by most modern browsers. For more information, I recommend you go read Matthew Johnson's blog post JavaScript precision timing.
Next Post Newer Post Previous Post Older Post Home

0 comments :

Post a Comment