← 中文资源

简体中文版本

Date.now 与 performance.now 的分工

Date.now 是墙钟整毫秒,会被校时拨动;performance.now 单调递增且带亚毫秒精度,量耗时必须用后者,timeOrigin 只负责锚定纪元起点。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

整个示例围绕函数 busyFor组织。 这个文件只在 while (performance.now() < deadline) checksum = (checksum + 1) % 1e9; 里循环。

使用要点

  • 演示输出是带标签的(performance.now elapsed:、Date.now elapsed:、Date.now is always an integer:),每个操作都会留下自己的一行标注。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 busyFor。

主要签名是 function busyFor(ms)

核心语句

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

代码示例

// 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);