Categories
JavaScript Answers

How to Measure the Time Taken by a JavaScript Function to Execute?

Spread the love

Sometimes, we’ve to find out how long a JavaScript function takes to run.

In this article, we’ll look at how to measure the time taken by a JavaScript function to run.

The performance.now() Method

One way to measure the time taken by a JavaScript to code to run is to use the performance.now method.

It returns the timestamp of the current time in milliseconds.

Therefore, to use it, we can write:

const t0 = performance.now()  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
const t1 = performance.now()  
console.log(t1 - t0, 'milliseconds')

We call performance.now before and after running our code.

Then we subtract the time after the code is run from the time before it’s run to get the run time of the code.

The console.time and console.timeEnd Methods

We can use the console.time method to start measure the time it takes for a piece of code to run.

Then we can use the console.timeEnd method to stop the measurement.

They both take a string as the argument that we can use as an identifier of what we’re measuring.

So to start the measurement, we call console.time with a string identifier.

And to end the measurement, we call console.timeEnd with the same string identifier that we used with console.time .

For instance, we can write:

console.time('loop')  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
console.timeEnd('loop')

After calling timeEnd , we should get the identifier string with the time between the console.time and console.timeEnd method calls logged in milliseconds.

Conclusion

We can measure the time it takes to run a piece of JavaScript with the performance interface or console methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *