How To Test Execution Time in JavaScript

Use console.time() and console.timeEnd()

How To Test Execution Time in JavaScript
Photo by Christina Kirschnerova on Unsplash

Are you curious about how fast (or slow) your code is running? Do you ever wonder which of two potential solutions is more performant?

Are you ever dissuaded from finding out because it’s too much of a hassle?

I know I am… or rather, I was, until I found a super simple, no-additional-imports-needed way to set up timers throughout my code.

I’m talking about two methods in the console library: .time() and .timeEnd()


What Is the ‘Console’ Library?

Console is a built-in library of basic JavaScript functionalities. We frequently use console.log() for testing and printing basic outputs, but did you know that .log() is only one of many methods in the console library?

An entire series of tutorials could be dedicated to the console library, but that is for another day. Just know that it has a variety of tools that make your JavaScript development life easier.

Introducing console.time() and console.timeEnd()

We will be using the methods .time() and .timeEnd() to start and stop our execution timer, respectively. Both methods take a single argument — a name to identify the timed process. If we want to call our execution test "function_timer" then we will execute console.time("function_timer") to start the timer and end it with console.timeEnd("function_timer"). The results will be printed to the console in milliseconds with the name given to the test.let scores = [99,45,28,94,86];console.time("max");
let max = Math.max(...scores);
console.timeEnd("max");// max: 0.284ms

Benefits of Using .time() and .timeEnd()

What’s great about using console.time() and console.timeEnd() is that they are natively available, meaning you do not need to import any additional libraries.

Additionally, there is no need to mess with JavaScript date objects.

But perhaps best of all, you can have multiple timers going at once and there is nothing wrong with them overlapping.let scores = [99,45,28,94,86];
let total = 0;console.time("outer-loop");
for(const score in scores) {
 console.time("inner-loop);
 total += score;
 console.timeEnd("inner-loop");
}
console.timeEnd("outer-loop");/*
inner-loop: 0.140ms
inner-loop: 0.021ms
inner-loop: 0.002ms
inner-loop: 0.002ms
inner-loop: 0.001ms
outer-loop: 2.045ms
*/

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe