console.table() function. Today, I want to show you another debugging method, more specifically one for measuring execution times: Say hello to
Measuring Execution Times the Classic Way
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
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
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):
Finally, here's IE 11, which only logs the duration if the console is open at that time:
To see a live demo of how your browser outputs the measured duration, just open the console now. I've taken the liberty to run the above script for you. Happy debugging!
A Closing Word on High-Precision Timing
If you need to measure time precisely, neither
There's a different API for that purpose, though: the Performance interface, which is implemented by most modern browsers.
Also, make sure to check out my other posts about the Chrome Developer Tools: