Date Now Versus Performance Now

Date.now is wall-clock whole milliseconds while performance.now is monotonic with sub-millisecond precision, so durations need the latter.

JavascriptData Integrity

Code

javascriptsnippet
24 lines
// Date.now() versus performance.now(): wall clock versus monotonic clock.
// Date.now can jump with NTP syncs and only resolves to whole milliseconds,
// so elapsed time must be measured with performance.now()
function busyFor(ms) {
  const deadline = performance.now() + ms;
  let checksum = 0;
  while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;
  return checksum;
}

const perfStart = performance.now();
busyFor(10);
const perfElapsed = performance.now() - perfStart;
console.log('performance.now elapsed:', perfElapsed.toFixed(3), 'ms');

const dateStart = Date.now();
busyFor(10);
const dateElapsed = Date.now() - dateStart;
console.log('Date.now elapsed:', dateElapsed, 'ms (whole ms only)');

console.log('Date.now is always an integer:', Number.isInteger(Date.now()));
console.log('performance.now never goes backwards:', performance.now() >= perfStart);
console.log('timeOrigin is epoch ms:', performance.timeOrigin > 1e12);
console.log('Date.now is epoch ms:', Date.now() > 1e12);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

performance.now elapsed: 14.785 ms
Date.now elapsed: 10 ms (whole ms only)
Date.now is always an integer: true
performance.now never goes backwards: true
timeOrigin is epoch ms: true
Date.now is epoch ms: true

How it works

The short read: the function busyFor, doing all the work.

One loop does the cycling here: while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.

Putting it to use

Signature: function busyFor(ms)

The file’s steps show up in the output as performance.now elapsed:, Date.now elapsed:, Date.now is always an integer:.

Core lines

while (performance.now() < deadline) checksum = (checksum + 1) % 1e9;
const perfElapsed = performance.now() - perfStart;
const dateElapsed = Date.now() - dateStart;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. The file defines `busyFor` at load time.