DEV Community

loading...

JavaScript Performance using console.time() & console.timeEnd()

3sanket3 profile image Sanket Patel ・1 min read

Many a times it's necessary to check the time your code is taking to execute. JavaScript runs on the client's local machine and we don't want our application to be sluggish even in the devices with lesser hardware configurations.

Previously, I was using the method of printing current timestamps to manually check how much time it took. Let's jump right into code:

let startTime = new Date().getTime();

console.log("started");

setTimeout(() => {
  console.log(
    "ended in " + (new Date().getTime() - startTime) + " milliseconds"
  );
}, 3000);

Output will be :

"started"
"ended in 3001 milliseconds"

But then I found that there are built-in methods that can help to accomplish the same. They are console.time('some text') and console.timeEnd('some text'). These can make our life so much easier to see elapsed times. A refactored version of the code sample above would be;

console.time("timer");

setTimeout(() => {
  console.timeEnd("timer");
}, 3000);

Output will be:

"timer: 3001.4951171875ms"

This is pretty clean and kind of a non-hacky way to test our code's execution time.

Hope you find it useful. Happy coding!

Thanks Ronak Baldha for reviewing the post.

Discussion (17)

pic
Editor guide
Collapse
bgadrian profile image
Adrian B.G.

I think that this is the definition of "hacky", you change the code you are trying to measure. Is like using console.log instead of breakpoints.

We used this method 5-10yrs ago when we do not have the required tools, but now you do not need them, you have dev tools developers.google.com/web/tools/ch...

Collapse
3sanket3 profile image
Sanket Patel Author

Yes @bgadrian , it is kind of, but a quick way to just check the time consumption of a piece of code. Actually I briefly checked the dev tool's performance feature after reading your comment but found profile seems to have too much application level performance analysis. May be I have to check more tutorials to go in deeper. I would appreciate if you have any suggestions for the same. Thank You!

Collapse
bgadrian profile image
Adrian B.G. • Edited

Ok but how would that help you? Most of the time you want to optimize the app or the golden path (or a specific action). To do that you have to find the bottleneck first then optimize it.
The idea is that you do not know what to improve until you benchmark the entire app.

There is a scenario when you want to measure a piece of code, when you do unit benchmarks, when you want to improve an algorithm and compare two versions in paralell. But Im sure there are better ways to do this in JS, like benchmark.js, the lib behind jsperf.com

// add tests
suite.add('old', function() {
  yourOldFunction();
})
.add('new', function() {
  yourNewFunction();
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': false });

The idea is Not to modify your code, but rather test it from the outside.
You can add performance tracking in your TEST files, which will not be bundled in the production.


Also I forgot to mention, the HTML5 added a new API with this purpose, to measure the performance: developer.mozilla.org/en-US/docs/W...

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

The difference is that console is a functionality added by the browser but the performance is a "native" tool.

Thread Thread
pranjalagnihot8 profile image
Pranjal Agnihotri {..❤️}

Hey @adrian , I want to just get the elapsed millisecond for a particular JS function in web-app, is there any simpler way to achieve this without using browser native API. Benchmark.js seems over kill for this use case.

Collapse
varoman profile image
varo manukyan

Unfortunately, this kind of performance measurements are useless.

  1. You can't measure the performance of the entire application
  2. Every time you re-run it will produce completely different results, so you can't event say how long it will take a particular function to run.

Never rely on measurements like this one and better use browser dev tools, they're great!

Collapse
3sanket3 profile image
Sanket Patel Author • Edited

Yes, I agree this is not something that can measure the performance of whole app, but as @dimpiax rightly said, can be useful just to check time consumption of the piece of code quickly.

I also appreciate the point you mentioned about the browser dev tool. I tried it after @bgadrian mentioned in a comment above. But in my brief experiment I found it with too much high level info, may be I need to check the official tutorials to get better idea. Would love to know if you have any reference. Thanks!

Collapse
dimpiax profile image
Dmytro Pylypenko

In case of unit tests measurement – current approach is perfect.

Collapse
bgadrian profile image
Adrian B.G.

Not really, is better to use a tool like benchmark.js and wrap your functions there, this way you avoid polluting your code and keep it away from the production bundles.

Thread Thread
dimpiax profile image
Dmytro Pylypenko

It depends on skills of developer, if he cannot write vanilla simple functions and doesn't know how to organize architecture and behavior of application, which produces polluting – then developer starts to use 3rd party libraries for trivial purposes.
If developer is skilled – it's enough to wrap using native functions, like console.time and console.timeEnd.

For example:

const measure = (label, closure) => { 
    console.time(label); 
    closure(); 
    console.timeEnd(label); 
}

measure('one', () => { 
    Array.from(Array(10000), (_, i) => i).map(v => Math.random(v)); 
})
Thread Thread
varoman profile image
varo manukyan • Edited

Please note, every time you re-run it will produce completely different results, so you can't event say how long it will take a particular function to run.

Unlike console.time(), benchmark allows you to run you suits lots of times, giving your more correct average results.

Or you can test your units with jsperf.com/

Thread Thread
dimpiax profile image
Dmytro Pylypenko

Of course, because processor allocates resources differently.
When we talk about measurement for unit tests or for performance function – time is the range of allowed min/max.

Thread Thread
bgadrian profile image
Adrian B.G.

I agree, the dev must know what a framework does, but framework or vanilla, the LOC used to benchmark (like performance or console) would be better to be in separate .js files, which are not bundled into the product.

Collapse
codevault profile image
Sergiu Mureşan

Thanks for the tip, that makes my life so much easier when trying to time something.

There's also console.table for printing out a variable as a table with properties and values being the columns.

Collapse
annarankin profile image
Anna Rankin

console.table blew my mind! 🤯Neat!

Collapse
3sanket3 profile image
Sanket Patel Author

That's great to hear.

Haven't checked console.table, will surely take a look. Thanks :)

Collapse
pranjalagnihot8 profile image
Pranjal Agnihotri {..❤️}

Got to know about this few days back, its really cool

Collapse
nateous profile image
Nate

Wow! I didn't know this existed, thank you!