How to Use Performance API in JavaScript for Accurate Timing
Use the
performance object in JavaScript to measure time intervals with high precision. Call performance.now() to get the current timestamp in milliseconds with decimals, which helps track how long code takes to run.Syntax
The Performance API provides the performance.now() method that returns a high-resolution timestamp in milliseconds. You can use it to measure elapsed time by recording start and end times.
performance.now(): Returns the current time in milliseconds with microsecond precision.- Subtract two timestamps to get the duration.
javascript
const start = performance.now(); // code to measure const end = performance.now(); const duration = end - start; console.log(`Duration: ${duration} ms`);
Example
This example shows how to measure the time taken by a loop that counts to 1 million using performance.now(). It prints the duration in milliseconds.
javascript
const start = performance.now(); let sum = 0; for (let i = 0; i < 1000000; i++) { sum += i; } const end = performance.now(); const duration = end - start; console.log(`Loop took ${duration.toFixed(3)} milliseconds.`);
Output
Loop took 10.123 milliseconds.
Common Pitfalls
Common mistakes when using the Performance API include:
- Using
Date.now()instead ofperformance.now(), which is less precise. - Not subtracting start time from end time, leading to incorrect duration.
- Measuring asynchronous code without awaiting completion.
Always ensure you measure the exact code block you want and use performance.now() for accuracy.
javascript
/* Wrong way: Using Date.now() */ const startWrong = Date.now(); // some code const endWrong = Date.now(); console.log(`Duration (wrong): ${endWrong - startWrong} ms`); /* Right way: Using performance.now() */ const startRight = performance.now(); // some code const endRight = performance.now(); console.log(`Duration (right): ${endRight - startRight} ms`);
Quick Reference
| Method | Description |
|---|---|
| performance.now() | Returns high-resolution timestamp in milliseconds. |
| performance.mark(name) | Creates a timestamp mark with a name. |
| performance.measure(name, startMark, endMark) | Measures duration between two marks. |
| performance.getEntriesByType(type) | Gets performance entries of a specific type. |
| performance.clearMarks(name) | Clears marks by name. |
| performance.clearMeasures(name) | Clears measures by name. |
Key Takeaways
Use performance.now() for precise time measurements in milliseconds with decimals.
Always subtract start time from end time to get the duration.
Avoid Date.now() for performance timing because it is less accurate.
Use performance.mark() and performance.measure() for advanced timing scenarios.
Measure only the code you want to analyze and handle async code carefully.