avatarGourav Kajal

Summarize

Use performance.now() to Measure Execution Speed

A better way to measure the performance of your code

Photo by Abhyuday Majhi on Unsplash

The performance.now() method in JavaScript can be used to test the performance of your code. This method can be used to check the execution time of the code.

It returns the millisecond value of time (of type double). The time since the execution began is represented by the returned value.

Before performance.now()

The ancient way to check the performance of your code is to use Date() before and after the execution of your code. The code below demonstrates this:

const start = new Date();
for(let i = 0; i < 100000; i++) {
    tasks[i].doSomethingHeavy();
}
const end = new Date();
const time = start.getTime() - end.getTime();
// use time to measure performance

This code is only for demonstration purposes. It might not execute when you try to.

So here, we save the time before executing the for loop in start variable and record the current time after the for loop execution in the end variable. Then we simply get the difference between start and end to find out how much time our for loop took to execute.

A Better Approach: Using performance.now

Now, have a look at below code snippet.

const start = performance.now();        // UPDATED
for(let i = 0; i < 100000; i++) {
    tasks[i].doSomethingHeavy();
}
const end = performance.now();           // UPDATED
const time = start - end;                // UPDATED
// use time to measure performance

The timestamps supplied by performance.now() are not limited to one-millisecond resolution, unlike other timing data available to JavaScript (for example, Date.now). Instead, they use floating-point values with microsecond precision to express times.

In contrast to Date.now(), the values provided by performance.now() increases at a steady rate regardless of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, the sum of performance.timing.navigationStart + performance.now() will be close to Date.now ().

To read more about performance.now(), click here.

This is it for this article. I hope you have learned something new today. You can follow me on Medium or connect with me on LinkedIn. To read more articles like this, stay tuned!

Thanks for reading!

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

Web Development
Programming
JavaScript
Front End Development
Coding
Recommended from ReadMedium