How could I calculate the FPS of a canvas game application? I've seen some examples, but none of them use requestAnimationFrame, and im not sure how to apply their solutions there. This is my code:
By the way, is there any library I could add to surpervise performance?
new Date()
This API has several flaws and is only useful for getting the current date + time. Not for measuring timespans.
The Date-API uses the operating system's internal clock, which is constantly updated and synchronized with NTP time servers. This means, that the speed / frequency of this clock is sometimes faster and sometimes slower than the actual time - and therefore not useable for measuring durations and framerates.
If someone changes the system time (either manually or due to DST), you could at least see the problem if a single frame suddenly needed an hour. Or a negative time. But if the system clock ticks 20% faster to synchronize with world-time, it is practically impossible to detect.
Also, the Date-API is very imprecise - often much less than 1ms. This makes it especially useless for framerate measurements, where one 60Hz frame needs ~17ms.
performance.now()
The Performance API has been specificly made for such use cases and can be used equivalently to new Date()
. Just take one of the other answers and replace new Date()
with performance.now()
, and you are ready to go.
Sources:
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
And for windows:
[The time service] adjusts the local clock rate to allow it to converge toward the correct time. If the time difference between the local clock and the [accurate time sample] is too large to correct by adjusting the local clock rate, the time service sets the local clock to the correct time.
https://technet.microsoft.com/en-us/library/cc773013(v=ws.10).aspx