performance.now() function and measure the time before and after your function executes.
In this article we’ll discuss how to measure code execution time and techniques to avoid some common pitfalls.
The High Resolution Time API offers a function, named
now() that returns a
DOMHighResTimeStamp object. It’s a floating point number that reflects the current time in milliseconds
accurate to a thousandth of a millisecond. Individually, the number doesn’t add much value to your analysis, but a difference between two such numbers gives an accurate description of how much time has passed.
In addition to the fact that it is more accurate than the built-in
Date object, it’s also “monotonic”. That means, in simple terms, that it’s not affected by the system (e.g. your laptop OS) periodically correcting the system time. In even simpler terms, defining two instances of
Date and calculating the difference isn’t representative of the time that has passed.
The mathematical definition of “monotonic” is
(of a function or quantity) varying in such a way that it either never decreases or never increases.
Another way of explaining it, is by trying to imagine using it around the times of the year when the clocks go forward or go back. For example, when the clocks in your country all agree to skip an hour for the sake of maximizing daytime sunshine. If you were to make a
Date instance before clocks go back an hour, and another
Date instance afterwards, looking at the difference it would say something like “1 hour and 3 seconds and 123 milliseconds”. With two instances of
performance.now() the difference would be “3 seconds 123 milliseconds and 456789 thousands of a millisecond”.
In this section, I won’t cover this API in detail. So if you want to learn more about it and see some example of its use, I suggest you to read the article Discovering the High Resolution Time API.