Javascript precision timing
I've been working on a web-based animation intensive application recently and needed to track the performance of certain routines, I started out by doing this dirty trick:
var startTime = new Date().getTime;
...
console.log((newDate()).getTime() - startTime)
The results really weren't that satisfactory and the resolution was a little poor, I had a few results return the same times even though they were executing synchoronously. And then I remembered the W3C High Resolution Timers API.
High Resolution Times
All we need to use to take advantage of the high resolution timer is to use window.performance.now() which will give you the number of milliseconds relative to window.performance.timing.navigationStart (which is the number of milliseconds since the start of time, 1970 of course). The values that this new API outputs are accurate to within 1000th of a millisecond.
The following code snippet will return a high resolution time
var t1 = window.performance.now();
...
var t2 = window.performance.now();
console.log(t2 - t1); // Number of milliseconds passed
I toyed around with this and thought it would be interesting to see the difference between the new way and the old way to calculate something fairly trivial like user-perceived page load times.
var newWay = window.performance.now();
var oldWay = new Date().getTime() - window.performance.timing.navigationStart;
console.log(String(newWay) + ' versus ' + String(oldWay));
The results showed some difference, but this could be explained away by saying that the browsers javascript engine could be doing anything between those two calls depending on what other asynchronous operations could be happenning.
One Last Thing
Since some browsers may not have finalized their implementation, you may find this shim handy which takes into account the different browser specific prefixes:
varnow = (function() {
varperformance = window.performance || {};
performance.now = (function() {
returnperformance.now ||
performance.webkitNow ||
performance.msNow ||
performance.oNow ||
performance.mozNow ||
function() {returnnewDate().getTime(); };
})();
returnperformance.now();
});
A footnote for Chrome
At the time of writing (23 August 2013) Chrome doesn't properly support high resolution times :( it does have a window.performance.now() method but try calling it a few times in the developer console - the times are almost always nears the very start of a second, or near the very end of a second. It's sad because Chrome (with Blink) is supposed to be leading the way with best developer practices, and simply by having a defective implementation of an API doesn't mean that the API is successfully implemented.
Really great resource. Thanks