Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue May 16 2023

How to time our code execution with console.time and console.timeEnd

In this guide we will show how we can time a piece of code, a function or code block in JavaScript using the built in console.time and console.timeEnd.

I personally just stumble on these functions, I have never seen or used them before. I have always created my own timing functions, so I was glad there was a built in support in JavaScript. Today, I will show how they are used.

Time our code

So, the usage are really simple. We will provide our time function with a label, and then when we are done, we will use timeEnd with the same label.

Example of measuring a loop

Below is a basic example of timing a loop that runs 100 million iterations

console.time("loop"); for (let i = 0; i < 100000000; i++) {} console.timeEnd("loop"); // loop: 48.154052734375 ms

Measure API calls

If we want to measure an API call, it could look like this

const fetchData = async () => { console.time("api-call"); await fetch("https://api.algobook.info/v1/city?search=Paris"); console.timeEnd("api-call"); // api-call: 683.156005859375 ms }; fetchData();

Outro

All right, that's it for this short guide on how to easily measure our codes execution time using built in timing functions in JavaScript.

It is always good to keep an eye of how effective our code is, to make sure it performs at its best. Utilities like this are great of encourage us developers to test out our code and see if any improves can be made.

Thanks for reading, and have a great day!

signatureTue May 16 2023
See all our articles