In our code, we were previously calculating the difference between to events like so:
var beginTime = new Date();
// Do stuff
var endTime = new Date();
var duration = endTime.getTime() - beginTime.getTime();
console.log("Job began at " + beginTime.toUTCString()
+ " and took " + duration + " milliseconds.");
This results in a human-readable string:
Job began at Thu Sep 28 2017 11:17:33 GMT-0500 (Central Daylight Time) and took 7000 milliseconds.
We've decided to switch to High Resolution Time by using the more reliable performance.now()
. However, we still want to be able have a human-readable UTC time string included.
Initially, we tried this:
var beginTime = performance.now();
// Do stuff
var endTime = performance.now();
var duration = endTime - beginTime;
console.log("Job began at " + new Date(beginTime).toUTCString()
+ " and took " + duration + " seconds.");
We are finding that the duration is accurate, but new Date(performance.now())
results in an inaccurate UTC value (at the time of this writing, it provides a date nearly 50 years in the past).
Job began at Wed Dec 31 1969 20:10:46 GMT-0600 (Central Standard Time) and took 7000 milliseconds.
Is there a better way to convert the output of performance.now()
to an accurate UTC string? It doesn't have to be the exact same format as new Date().toUTCString()
, but it should be human-readable.
It can be done like this:
const t0 = performance.now();
// measured job here
const t1 = performance.now(),
t0Date = new Date(performance.timing.navigationStart + t0).toUTCString();
console.log(`Job began at ${t0Date} and took ${t1 - t0} milliseconds.`);
/* Console formatting only */
.as-console-wrapper { top: 0; }
Note however that after performance.now()
MDN page (emphasis mine):
(…)
performance.timing.navigationStart + performance.now()
will be approximately equal toDate.now()
.
For me, it's within one second of actual time start.