Calculate time taken by a function to be executed in Javascript
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +28K Followers | Now Hiring!
In this post I will show you how to calculate or measure the time that taken by a javascript function to be executed.
As we know that Javascript console has to functions console.time() and console.timeEnd()
Let’s have an example to make things more clear:
const fact = (number) =>
? ? if (number < 1) {
? ? ? ? return 1;
? ? }
? ? else {
? ? ? ? return number * fact(number - 1);
? ? }
}
Now we want to calculate the time of execution for this function in order to do this we can wrap this function between?console.time()?and?console.timeEnd()?which will display the execution time on?stdout
console.time('Factorial'
fact(10);
console.timeEnd('Factorial');)
Output of the above code should be like:
Factorial: 0.175ms
If you like to reuse this, you will have to create like a helper function to be able to reuse it later.
const measure = (label, fn) =>
? ? console.time(label);
? ? fn();
? ? console.timeEnd(label);
}
Call helper function:
measure('Factorial', () => {? ?
?fact(10);
?})?