Workers ランタイムは、タイミングとパフォーマンスの計測、およびサブリクエストやそのほかの操作の所要時間の計測に使う Performance API ↗ の一部をサポートしています。
performance.now() メソッド ↗ は、performance.timeOrigin からの経過時間をミリ秒のタイムスタンプとして返します。
Worker を Cloudflare にデプロイすると、Spectre 攻撃を緩和するセキュリティ対策として、performance.now() ↗ や Date.now() ↗ を含むタイマーを返す API は、I/O が発生したあとでしか進みません。次の例を見てください。
const start = performance.now();
for (let i = 0; i < 1e6; i++) {
// do expensive work
}
const end = performance.now();
const timing = end - start; // 0const 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 ↗ API は、ほかの計測の基準になるベースラインのタイムスタンプを返す読み取り専用プロパティです。
Workers ランタイムでは、timeOrigin プロパティは 0 を返します。