How to Measure Function Execution Duration
Measuring the execution time of a function can provide valuable insights into performance optimizations. There are several approaches to achieve this measurement.
Using performance.now() for Real-Time Performance Measurement
The modern approach for timing function execution is to utilize the performance.now() API. It returns the time elapsed since the start of the navigation in high-resolution milliseconds. To use it effectively:
In Node.js, it's necessary to import the performance class using const { performance } = require('perf_hooks');.
Using console.time for Simple Time Measurement
The console.time method offers a straightforward way to measure execution time. However, it supports only one measurement at a time:
The string passed to time() and timeEnd() must match to properly stop the timer. Refer to the MDN or Node.js documentation for detailed explanations.
The above is the detailed content of How Can I Efficiently Measure JavaScript Function Execution Time?. For more information, please follow other related articles on the PHP Chinese website!