Modern browsers and the Node.js platform provide various API’s to measure code execution time.
1. Date object
The easiest way to track execution time is to use a date object. Using
Date.now() that returns the total number of milliseconds elapsed since the Unix epoch, we can store the value before and after the execution of the function to be measured and then get the difference of the two.
2. Console time
Another easy solution is to use a console timer. The
console.time() method starts a timer with a label. And a subsequent call to the
console.timeEnd() method with the same label will output the time elapsed since the method was started.
3. Performance timers
Console timers do not provide high accuracy. If we want accuracy in 1-millisecond increments, we can use high-resolution timers like
performance.now(). It also avoids some synchronization issues with the system clock.
Note: If measuring in Node,
process.hrtime.bigint() returns accuracy in nanoseconds.
To ensure the execution of a function is fast enough, it can be made a part of our unit tests. Many frameworks (Jest, Jasmine, etc.) allow the setting of a timeout for the execution of a test. The timeout feature can then be used to fail a test if the method takes longer to execute.