Lập trình · 23/10/2026

JavaScript Date.now vs performance.now: Choose the Right Clock for Durations

When an operation happened and how long it took are different measurements. Date.now serves timestamps, while performance.now suits duration measurement within one execution context. Mixing clocks or purposes makes results misleading.

JavaScript Date.now và performance.now: chọn đồng hồ đúng để đo thời lượng

When an operation happened and how long it took are different measurements. Date.now serves timestamps, while performance.now suits duration measurement within one execution context. Mixing clocks or purposes makes results misleading.

1. Wall-clock subtraction can include clock adjustments

// Simulated wall-clock readings, not a real clock adjustment.
const startMs = 10_000;
const endMs = 9_500;
console.log(endMs - startMs); // -500

This simulates a clock moving backward without changing the machine's clock. Date.now returns milliseconds since the Unix epoch, and system-clock adjustments can affect wall-clock measurements.

Timestamps remain useful for event records and log correlation. For “how long did this operation take?”, select a duration clock instead of treating every timestamp difference as execution time.

2. Use the same monotonic clock at both boundaries

const started = performance.now();
const value = await Promise.resolve('ready');
const elapsedMs = performance.now() - started;
console.log(value); // ready
console.log(Number.isFinite(elapsedMs)); // true
console.log(elapsedMs >= 0); // true

performance.now uses a monotonic clock unaffected by wall-clock adjustments. Its origin is not the Unix epoch for direct use with new Date. In Node.js, zero represents process startup.

Do not subtract performance.now from Date.now, or directly compare performance.now values from different processes. Shared units do not establish a shared origin. Store timestamp and durationMs as separate fields when both are required.

3. Inject a clock for deterministic tests

async function measureTask(task, now = () => performance.now()) {
  const started = now();
  const value = await task();
  return { value, durationMs: now() - started };
}
const readings = [100, 125];
const result = await measureTask(
  async () => 'done',
  () => readings.shift()
);
console.log(result.value); // done
console.log(result.durationMs); // 25

The fake clock produces a fixed 25 ms without real waiting. It verifies arithmetic, not performance. Injected clocks must return finite nondecreasing numbers in consistent units; this illustrative helper trusts that caller contract.

task must return a value or a Promise representing the complete operation. Awaiting it includes waiting for successful settlement. If task throws or rejects, the helper propagates the reason and returns no duration record. Failure-duration reporting requires an additional observation path.

4. Define what the interval includes

A task that launches work without returning its Promise can stop the measurement too early. Timing a fetch call may exclude body reading or transformation when those steps occur outside the measured task. Choose boundaries according to the question being investigated.

Elapsed duration is not automatically CPU time. It can include I/O waits, scheduling and other activity during the interval. One short sample cannot establish an optimization win; use representative inputs, repeated samples and suitable aggregation.

Clock resolution may be restricted. Check sleep behavior on target environments if the product depends on it. These examples do not establish cross-platform precision or comparability between machines.

5. Review timing instrumentation

  • Do you need an event timestamp or a duration?
  • Do both boundaries share a clock, units and context?
  • Does the awaited Promise cover all intended work?
  • Must failures be measured too?
  • Are fake-clock tests clearly distinguished from benchmarks?

All six bilingual blocks ran with Node.js. Additional checks cover synchronous results, asynchronous work and original-error propagation. System-clock adjustments, sleep and production load were not tested.

Discussion

Comments 0

Sign in to comment

You need an account to join the discussion and reply to other readers.

Sign inRegister

No comments yet. Be the first to share your thoughts.