How to measure execution time of a function/instruction/whole program in JavaScript ?

Abdelmalek Ennani
2 min readApr 11, 2022

--

Sometimes we want to know how long our program takes to execute, where it comes from a cool method called console. Time ()

Basically, the method console.time()helps us track an operation duration, but unfortunately, we can only use it in our development phase, so don’t rely on it in the production phase.

now let’s demonstrate how it works, The console.time() method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.

fore example let’s track how long a function that’s help us to alert “Hello world” takes to execute.
Firstly, we have to put console.time(param) before the function Invocation
like this :

console.time("our timer");function sayHi() {
alert('hello world')
}
sayHi()
console.timeEnd("our timer");

you may notice that console.time("our timer") has an argument called “our timer” (you can give it whatever you want) we use this argument to identify our timer due to that we can have more than one timer in our program (for example we keep track other functions or instruction which means we may have other console.time(param).

we use console.timeEnd(param) with the same argument that we gave to our console.time(param) to tell the program to stop the timer and print out the result in the console.

To see the result of the previous example (program) you have to open your console by pressing F12 on your machine and you will something like that :

which means our function takes 20371.73388671875 ms to execute

if you want to measure execution time of a whole program you should use the same method, put your program between console.time(param) and console.time(param) and don’t forget to give them the same argument.

--

--

Abdelmalek Ennani

👨‍💻 Software engineering student 🔥 JavaScript lover ☕ ReactJs 👩‍🔧 @redux/toolkit react-refux 🧠 Laravel tinker 🔥