Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

パフォーマンスとタイマー

最終更新 Markdown で表示Agent セットアップ

背景

Workers ランタイムは、タイミングとパフォーマンスの計測、およびサブリクエストやそのほかの操作の所要時間の計測に使う Performance API の一部をサポートしています。

performance.now()

performance.now() メソッド は、performance.timeOrigin からの経過時間をミリ秒のタイムスタンプとして返します。

Worker を Cloudflare にデプロイすると、Spectre 攻撃を緩和するセキュリティ対策として、performance.now()Date.now() を含むタイマーを返す API は、I/O が発生したあとでしか進みません。次の例を見てください。

時刻は止まります。start と 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
start と 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() の呼び出しで囲むと、サブリクエスト、KV からのキー取得、R2 からのオブジェクト取得、Worker 内のそのほかの I/O の所要時間を計測できます。

一方、ローカル開発では、I/O の有無に関係なくタイマーが進みます。I/O を伴わない CPU 負荷の高いコードの所要時間を測りたい場合は、Wrangler で Worker をローカル実行します。Wrangler はオープンソースの Workers ランタイム workerd を使います。Cloudflare へデプロイした Worker が動くランタイムと同じです。

performance.timeOrigin

performance.timeOrigin API は、ほかの計測の基準になるベースラインのタイムスタンプを返す読み取り専用プロパティです。

Workers ランタイムでは、timeOrigin プロパティは 0 を返します。

役に立ちましたか?