Calculate time taken by a function to be executed in Javascript

Calculate time taken by a function to be executed in Javascript

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()

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

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);
 })

Share this post

Leave a Reply

Your email address will not be published.