How to measure execution time of javascript function

In this post, I will show you how to measure the execution time of any function in Javascript.
Javascript console API has two functions console.time and console.timeEnd

  • console.time - start the timer
  • console.timeEnd - Stops a timer that was previously started by calling console.time() and prints the result to stdout:

for example, let’s suppose you have the following javascript function, which calculates the factorial of a given number

const fact = (number) => {
    if (number < 1) {
        return 1;
    }
    else {
        return number * fact(number - 1);
    }
}

and you want to calculate the execution time of the function.
You 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');

if you execute the above script, you will see the following output

Factorial: 0.175ms

This approach is not reusable. You can create one helper function as below

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

and use like below

measure('Factorial', () => {    
 fact(10);
 })

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru