Measuring Time with Precision in JavaScript

Measuring Time with Sub-Millisecond Precision in JavaScript

Time measurement is a crucial aspect of performance optimization and profiling in JavaScript. Whether you’re benchmarking code execution, tracking user interactions, or monitoring network requests, having precise timing data is essential. JavaScript offers a powerful tool for measuring time with sub-millisecond precision: performance.now(). In this article, we’ll explore how to use this method effectively.

Understanding performance.now()

The performance.now() method is part of the Browser Timing API and provides a high-resolution time stamp with sub-millisecond precision. This API is available in most modern web browsers, making it a valuable tool for web developers.1

Here’s a quick overview of how performance.now() works:

  • When you call performance.now(), it returns a DOMHighResTimeStamp, which is a double-precision floating-point value representing the number of milliseconds that have elapsed since the page started loading.
  • The returned value includes sub-millisecond fractions, allowing you to measure time with extreme precision.
  • The timer is monotonically increasing and not subject to clock adjustments, making it reliable for performance measurement.

Now that we understand the basics, let’s dive into practical usage.

Measuring Code Execution Time

One common use case for performance.now() is measuring how long it takes for a block of code to execute. Here’s a simple example:2

// Start the timer
const startTime = performance.now();

// Some code you want to measure
for (let i = 0; i < 1000000; i++) {
  // Perform some task
}

// End the timer
const endTime = performance.now();

// Calculate the time difference in sub-milliseconds
const timeDifference = endTime - startTime;

console.log(`Time difference: ${timeDifference} milliseconds`);

In this code snippet:

  • We start the timer by capturing the current timestamp in startTime.
  • We execute the code we want to measure, in this case, a loop that performs a task one million times.
  • After the code execution, we capture the current timestamp in endTime.
  • We calculate the time difference by subtracting startTime from endTime, giving us the execution time with sub-millisecond precision.

Profiling User Interactions

performance.now() can also be used to profile user interactions, such as measuring how long it takes for a button click handler to execute. This information can help identify performance bottlenecks and improve the user experience.

const button = document.getElementById('myButton');

button.addEventListener('click', () => {
  // Start the timer when the button is clicked
  const startTime = performance.now();

  // Perform some task
  // ...

  // End the timer after the task is complete
  const endTime = performance.now();

  const timeDifference = endTime - startTime;

  console.log(`Button click took ${timeDifference} milliseconds`);
});

In this example:

  • We attach a click event listener to a button element.
  • Inside the click handler, we start the timer with performance.now() when the button is clicked.
  • After performing the desired task, we capture the end time and calculate the time difference.
  • We log the time it took for the button click handler to execute.

Measuring Network Request Time

You can also use performance.now() to measure the time it takes for network requests to complete. This can be valuable for monitoring API calls or resource loading times.34

const apiUrl = 'https://api.example.com/data';

// Start the timer before making the network request
const startTime = performance.now();

fetch(apiUrl)
  .then((response) => response.json())
  .then((data) => {
    // End the timer when the request is complete
    const endTime = performance.now();

    const timeDifference = endTime - startTime;

    console.log(`Network request took ${timeDifference} milliseconds`);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

In this case:

  • We start the timer before initiating the network request with fetch().
  • When the request completes successfully, we capture the end time and calculate the time difference.
  • We log the time it took for the network request to finish.

Conclusion

performance.now() is a powerful tool for measuring time with sub-millisecond precision in JavaScript. Whether you’re optimizing code, profiling user interactions, or monitoring network requests, this method provides accurate timing data to help you identify and resolve performance issues. By incorporating performance.now() into your development toolkit, you can gain valuable insights into the performance of your web applications.

References

  1. Performance – Web APIs | MDN. (2023, February 19). MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/API/Performance ↩︎
  2. Why does performance.now() and Chrome’s performance tools show different results? (n.d.). Stack Overflow. https://stackoverflow.com/questions/48212245/why-does-performance-now-and-chromes-performance-tools-show-different-results ↩︎
  3. Ayebola, J. (2023, November 3). How to Call an API in JavaScript – with Examples. freeCodeCamp.org. https://www.freecodecamp.org/news/make-api-calls-in-javascript/ ↩︎
  4. Pelakauskas, A., & Pelakauskas, A. (2022, June 2). How to make HTTP requests in Node.js with Fetch API. https://oxylabs.io/blog/nodejs-fetch-api ↩︎
Published