跳转到内容
搜索文档

Performance 与计时器

最后更新 查看 MarkdownAgent 设置

背景

Workers 运行时支持 Performance API 的子集,用于测量计时和性能,以及子请求和其他操作的耗时。

performance.now()

performance.now() 方法 返回以毫秒为单位的时间戳,表示自 performance.timeOrigin 以来经过的时间。

当 Worker 部署到 Cloudflare 时,作为 缓解 Spectre 攻击 的安全措施,返回计时器的 API(包括 performance.now()Date.now())仅在发生 I/O 后才会前进或递增。请考虑以下示例:

Time is frozen — start will have the exact same value as end.typescript
const start = performance.now();
for (let i = 0; i < 1e6; i++) {
  // do expensive work
}
const end = performance.now();
const timing = end - start; // 0
Time advances, because a subrequest has occurred between start and end.typescript
const start = performance.now();
const response = await fetch("https://developers.cloudflare.com/");
const end = performance.now();
const timing = end - start; // duration of the subrequest to developers.cloudflare.com

通过在子请求前后调用 performance.now()Date.now() API,您可以测量子请求的耗时、从 KV 获取键的耗时、从 R2 获取对象的耗时,或 Worker 中任何其他形式的 I/O 耗时。

但在本地开发中,无论是否发生 I/O,计时器都会递增。这意味着如果您需要测量不涉及 I/O 的 CPU 密集型代码的耗时,可以通过 Wrangler 在本地运行 Worker,它使用开源 Workers 运行时 workerd——与部署到 Cloudflare 时 Worker 使用的运行时相同。

performance.timeOrigin

performance.timeOrigin API 是一个只读属性,返回用于其他测量基准的时间戳。

在 Workers 运行时中,timeOrigin 属性返回 0。

这篇文档对您有帮助吗?