パフォーマンス計測 API#

安定性: 2 - Stable

ソースコード: lib/perf_hooks.js

このモジュールは、W3C Web Performance API のサブセットの実装と、Node.js 固有のパフォーマンス測定のための追加 API を提供します。

Node.js は、以下の Web Performance API をサポートしています。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((items) => {
  console.log(items.getEntries()[0].duration);
  performance.clearMarks();
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');

performance.mark('A');
doSomeLongRunningProcess(() => {
  performance.measure('A to Now', 'A');

  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
});const { PerformanceObserver, performance } = require('node:perf_hooks');

const obs = new PerformanceObserver((items) => {
  console.log(items.getEntries()[0].duration);
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');

performance.mark('A');
(async function doSomeLongRunningProcess() {
  await new Promise((r) => setTimeout(r, 5000));
  performance.measure('A to Now', 'A');

  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
})();

perf_hooks.performance#

現在の Node.js インスタンスからパフォーマンスメトリクスを収集するために使用できるオブジェクトです。ブラウザの window.performance に似ています。

performance.clearMarks([name])#

name が指定されていない場合、パフォーマンスタイムラインからすべての PerformanceMark オブジェクトを削除します。name が指定されている場合、指定された名前のマークのみを削除します。

performance.clearMeasures([name])#

name が指定されていない場合、パフォーマンスタイムラインからすべての PerformanceMeasure オブジェクトを削除します。name が指定されている場合、指定された名前のメジャーのみを削除します。

performance.clearResourceTimings([name])#

name が指定されていない場合、リソースタイムラインからすべての PerformanceResourceTiming オブジェクトを削除します。name が指定されている場合、指定された名前のリソースのみを削除します。

performance.eventLoopUtilization([utilization1[, utilization2]])#

  • utilization1 <Object> 以前の eventLoopUtilization() 呼び出しの結果。
  • utilization2 <Object> utilization1 より前の eventLoopUtilization() 呼び出しの結果。
  • 戻り値: <Object>

eventLoopUtilization() メソッドは、イベントループがアイドル状態であった時間とアクティブであった時間の累積期間を高分解能ミリ秒タイマーとして含むオブジェクトを返します。utilization の値は、計算されたイベントループ使用率 (ELU) です。

メインスレッドでブートストラップがまだ完了していない場合、プロパティの値は 0 になります。ELU は、ワーカースレッドではイベントループ内でブートストラップが行われるため、すぐに利用可能です。

utilization1utilization2 はどちらもオプションのパラメータです。

utilization1 が渡された場合、現在の呼び出しの activeidle の時間との差分、および対応する utilization の値が計算されて返されます (process.hrtime() と同様です)。

utilization1utilization2 の両方が渡された場合、2つの引数の間で差分が計算されます。これは便利なオプションです。なぜなら、process.hrtime() とは異なり、ELU の計算は単純な引き算よりも複雑だからです。

ELU は CPU 使用率に似ていますが、CPU 使用率ではなくイベントループの統計のみを測定します。これは、イベントループがイベントループのイベントプロバイダー (例: epoll_wait) の外で費やした時間の割合を表します。他の CPU アイドル時間は考慮されません。以下は、ほとんどアイドル状態のプロセスが高い ELU を持つ例です。

import { eventLoopUtilization } from 'node:perf_hooks';
import { spawnSync } from 'node:child_process';

setImmediate(() => {
  const elu = eventLoopUtilization();
  spawnSync('sleep', ['5']);
  console.log(eventLoopUtilization(elu).utilization);
});'use strict';
const { eventLoopUtilization } = require('node:perf_hooks').performance;
const { spawnSync } = require('node:child_process');

setImmediate(() => {
  const elu = eventLoopUtilization();
  spawnSync('sleep', ['5']);
  console.log(eventLoopUtilization(elu).utilization);
});

このスクリプトを実行している間、CPU はほとんどアイドル状態ですが、utilization の値は 1 です。これは、child_process.spawnSync() の呼び出しがイベントループの進行をブロックするためです。

以前の eventLoopUtilization() 呼び出しの結果ではなく、ユーザー定義のオブジェクトを渡すと、未定義の動作につながります。戻り値は、イベントループの正しい状態を反映することを保証しません。

performance.getEntries()#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。特定のタイプまたは特定の名前のパフォーマンスエントリのみに関心がある場合は、performance.getEntriesByType()performance.getEntriesByName() を参照してください。

performance.getEntriesByName(name[, type])#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.namename と等しく、オプションで performanceEntry.entryTypetype と等しいエントリが含まれます。

performance.getEntriesByType(type)#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.entryTypetype と等しいエントリが含まれます。

performance.mark(name[, options])#

  • name <string>
  • options <Object>
    • detail <any> マークに含める追加のオプションの詳細。
    • startTime <number> マーク時間として使用するオプションのタイムスタンプ。デフォルト: performance.now()

パフォーマンスタイムラインに新しい PerformanceMark エントリを作成します。PerformanceMarkPerformanceEntry のサブクラスで、performanceEntry.entryType は常に 'mark' であり、performanceEntry.duration は常に 0 です。パフォーマンスマークは、パフォーマンスタイムライン上の特定の重要な瞬間をマークするために使用されます。

作成された PerformanceMark エントリは、グローバルパフォーマンスタイムラインに配置され、performance.getEntriesperformance.getEntriesByNameperformance.getEntriesByType を使ってクエリできます。観測が実行されたら、エントリは performance.clearMarks を使ってグローバルパフォーマンスタイムラインから手動でクリアする必要があります。

performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])#

このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。

リソースタイムラインに新しい PerformanceResourceTiming エントリを作成します。PerformanceResourceTimingPerformanceEntry のサブクラスで、performanceEntry.entryType は常に 'resource' です。パフォーマンスリソースは、リソースタイムライン上の瞬間をマークするために使用されます。

作成された PerformanceMark エントリは、グローバルリソースタイムラインに配置され、performance.getEntriesperformance.getEntriesByNameperformance.getEntriesByType を使ってクエリできます。観測が実行されたら、エントリは performance.clearResourceTimings を使ってグローバルパフォーマンスタイムラインから手動でクリアする必要があります。

performance.measure(name[, startMarkOrOptions[, endMark]])#

  • name <string>
  • startMarkOrOptions <string> | <Object> オプション。
    • detail <any> メジャーに含める追加のオプションの詳細。
    • duration <number> 開始時刻と終了時刻の間の時間。
    • end <number> | <string> 終了時刻として使用するタイムスタンプ、または以前に記録されたマークを識別する文字列。
    • start <number> | <string> 開始時刻として使用するタイムスタンプ、または以前に記録されたマークを識別する文字列。
  • endMark <string> オプション。startMarkOrOptions<Object> の場合は省略しなければなりません。

パフォーマンスタイムラインに新しい PerformanceMeasure エントリを作成します。PerformanceMeasurePerformanceEntry のサブクラスで、performanceEntry.entryType は常に 'measure' であり、performanceEntry.durationstartMarkendMark の間に経過したミリ秒数を測定します。

startMark 引数は、パフォーマンスタイムライン内の既存の PerformanceMark を識別するか、または PerformanceNodeTiming クラスによって提供されるタイムスタンププロパティのいずれかを識別することができます。指定された名前の startMark が存在しない場合、エラーがスローされます。

オプションの endMark 引数は、パフォーマンスタイムライン内の既存の PerformanceMark または PerformanceNodeTiming クラスによって提供されるタイムスタンププロパティのいずれかを識別しなければなりません。パラメータが渡されない場合、endMarkperformance.now() になります。それ以外の場合で、指定された名前の endMark が存在しない場合は、エラーがスローされます。

作成された PerformanceMeasure エントリは、グローバルパフォーマンスタイムラインに配置され、performance.getEntriesperformance.getEntriesByNameperformance.getEntriesByType を使ってクエリできます。観測が実行されたら、エントリは performance.clearMeasures を使ってグローバルパフォーマンスタイムラインから手動でクリアする必要があります。

performance.nodeTiming#

このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。

特定の Node.js の運用マイルストーンに関するパフォーマンスメトリクスを提供する PerformanceNodeTiming クラスのインスタンス。

performance.now()#

現在の高分解能ミリ秒タイムスタンプを返します。0 は現在の node プロセスの開始を表します。

performance.setResourceTimingBufferSize(maxSize)#

グローバルなパフォーマンスリソースタイミングバッファのサイズを、指定された数の "resource" タイプのパフォーマンスエントリオブジェクトに設定します。

デフォルトでは、最大バッファサイズは 250 に設定されています。

performance.timeOrigin#

timeOrigin は、現在の node プロセスが開始した高分解能ミリ秒タイムスタンプを、Unix 時間で指定します。

performance.timerify(fn[, options])#

  • fn <Function>
  • options <Object>
    • histogram <RecordableHistogram> 実行時間をナノ秒単位で記録する、perf_hooks.createHistogram() を使用して作成されたヒストグラムオブジェクト。

このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。

関数を、ラップされた関数の実行時間を測定する新しい関数でラップします。タイミングの詳細にアクセスするためには、PerformanceObserver'function' イベントタイプにサブスクライブされている必要があります。

import { performance, PerformanceObserver } from 'node:perf_hooks';

function someFunction() {
  console.log('hello world');
}

const wrapped = performance.timerify(someFunction);

const obs = new PerformanceObserver((list) => {
  console.log(list.getEntries()[0].duration);

  performance.clearMarks();
  performance.clearMeasures();
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

// A performance timeline entry will be created
wrapped();const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

function someFunction() {
  console.log('hello world');
}

const wrapped = performance.timerify(someFunction);

const obs = new PerformanceObserver((list) => {
  console.log(list.getEntries()[0].duration);

  performance.clearMarks();
  performance.clearMeasures();
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

// A performance timeline entry will be created
wrapped();

ラップされた関数がプロミスを返す場合、プロミスに finally ハンドラがアタッチされ、finally ハンドラが呼び出されたときに実行時間が報告されます。

performance.toJSON()#

performance オブジェクトの JSON 表現であるオブジェクトです。ブラウザの window.performance.toJSON に似ています。

イベント: 'resourcetimingbufferfull'#

'resourcetimingbufferfull' イベントは、グローバルなパフォーマンスリソースタイミングバッファがいっぱいになったときに発生します。イベントリスナー内で performance.setResourceTimingBufferSize() を使用してリソースタイミングバッファのサイズを調整するか、performance.clearResourceTimings() を使用してバッファをクリアすることで、パフォーマンスタイムラインバッファにさらにエントリを追加できるようになります。

クラス: PerformanceEntry#

このクラスのコンストラクタは、ユーザーに直接公開されていません。

performanceEntry.duration#

このエントリに対して経過した合計ミリ秒数。この値は、すべての Performance Entry タイプで意味があるわけではありません。

performanceEntry.entryType#

パフォーマンスエントリのタイプ。以下のいずれかです。

  • 'dns' (Node.js のみ)
  • 'function' (Node.js のみ)
  • 'gc' (Node.js のみ)
  • 'http2' (Node.js のみ)
  • 'http' (Node.js のみ)
  • 'mark' (Web で利用可能)
  • 'measure' (Web で利用可能)
  • 'net' (Node.js のみ)
  • 'node' (Node.js のみ)
  • 'resource' (Web で利用可能)

performanceEntry.name#

パフォーマンスエントリの名前。

performanceEntry.startTime#

パフォーマンスエントリの開始時刻を示す高分解能ミリ秒タイムスタンプ。

クラス: PerformanceMark#

Performance.mark() メソッドを介して作成されたマークを公開します。

performanceMark.detail#

Performance.mark() メソッドで作成時に指定された追加の詳細。

クラス: PerformanceMeasure#

Performance.measure() メソッドを介して作成されたメジャーを公開します。

このクラスのコンストラクタは、ユーザーに直接公開されていません。

performanceMeasure.detail#

Performance.measure() メソッドで作成時に指定された追加の詳細。

クラス: PerformanceNodeEntry#

このクラスは Node.js による拡張です。Web ブラウザでは利用できません。

詳細な Node.js タイミングデータを提供します。

このクラスのコンストラクタは、ユーザーに直接公開されていません。

performanceNodeEntry.detail#

entryType に固有の追加の詳細。

performanceNodeEntry.flags#

安定性: 0 - 非推奨: 代わりに performanceNodeEntry.detail を使用してください。

performanceEntry.entryType'gc' の場合、performance.flags プロパティにはガベージコレクション操作に関する追加情報が含まれます。値は以下のいずれかです。

  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE

performanceNodeEntry.kind#

安定性: 0 - 非推奨: 代わりに performanceNodeEntry.detail を使用してください。

performanceEntry.entryType'gc' の場合、performance.kind プロパティは発生したガベージコレクション操作のタイプを識別します。値は以下のいずれかです。

  • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
  • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
  • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
  • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB

ガベージコレクション ('gc') の詳細#

performanceEntry.type'gc' の場合、performanceNodeEntry.detail プロパティは2つのプロパティを持つ <Object> になります。

  • kind <number> 以下のいずれかです。
    • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
    • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
    • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
    • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
  • flags <number> 以下のいずれかです。
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE

HTTP ('http') の詳細#

performanceEntry.type'http' の場合、performanceNodeEntry.detail プロパティは追加情報を含む <Object> になります。

performanceEntry.nameHttpClient の場合、detail には reqres のプロパティが含まれます。req プロパティは methodurlheaders を含む <Object> であり、res プロパティは statusCodestatusMessageheaders を含む <Object> です。

performanceEntry.nameHttpRequest の場合、detail には reqres のプロパティが含まれます。req プロパティは methodurlheaders を含む <Object> であり、res プロパティは statusCodestatusMessageheaders を含む <Object> です。

これにより追加のメモリオーバーヘッドが発生する可能性があるため、診断目的でのみ使用し、本番環境でデフォルトで有効にしないでください。

HTTP/2 ('http2') の詳細#

performanceEntry.type'http2' の場合、performanceNodeEntry.detail プロパティは追加のパフォーマンス情報を含む <Object> になります。

performanceEntry.nameHttp2Stream の場合、detail には以下のプロパティが含まれます。

  • bytesRead <number> この Http2Stream で受信した DATA フレームのバイト数。
  • bytesWritten <number> この Http2Stream で送信した DATA フレームのバイト数。
  • id <number> 関連する Http2Stream の識別子。
  • timeToFirstByte <number> PerformanceEntrystartTime と最初の DATA フレームの受信との間に経過したミリ秒数。
  • timeToFirstByteSent <number> PerformanceEntrystartTime と最初の DATA フレームの送信との間に経過したミリ秒数。
  • timeToFirstHeader <number> PerformanceEntrystartTime と最初のヘッダーの受信との間に経過したミリ秒数。

performanceEntry.nameHttp2Session の場合、detail には以下のプロパティが含まれます。

  • bytesRead <number> この Http2Session で受信したバイト数。
  • bytesWritten <number> この Http2Session で送信したバイト数。
  • framesReceived <number> Http2Session によって受信された HTTP/2 フレームの数。
  • framesSent <number> Http2Session によって送信された HTTP/2 フレームの数。
  • maxConcurrentStreams <number> Http2Session の存続期間中に同時に開かれていたストリームの最大数。
  • pingRTT <number> PING フレームの送信とその確認応答の受信との間に経過したミリ秒数。Http2SessionPING フレームが送信された場合にのみ存在します。
  • streamAverageDuration <number> すべての Http2Stream インスタンスの平均期間 (ミリ秒単位)。
  • streamCount <number> Http2Session によって処理された Http2Stream インスタンスの数。
  • type <string> Http2Session のタイプを識別するための 'server' または 'client' のいずれか。

Timerify ('function') の詳細#

performanceEntry.type'function' の場合、performanceNodeEntry.detail プロパティは、計測対象の関数への入力引数をリストする <Array> になります。

Net ('net') の詳細#

performanceEntry.type'net' の場合、performanceNodeEntry.detail プロパティは追加情報を含む <Object> になります。

performanceEntry.nameconnect の場合、detail には hostport のプロパティが含まれます。

DNS ('dns') の詳細#

performanceEntry.type'dns' の場合、performanceNodeEntry.detail プロパティは追加情報を含む <Object> になります。

performanceEntry.namelookup の場合、detail には hostnamefamilyhintsverbatimaddresses のプロパティが含まれます。

performanceEntry.namelookupService の場合、detail には hostporthostnameservice のプロパティが含まれます。

performanceEntry.namequeryxxx または getHostByAddr の場合、detail には hostttlresult のプロパティが含まれます。result の値は queryxxx または getHostByAddr の結果と同じです。

クラス: PerformanceNodeTiming#

このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。

Node.js 自体のタイミング詳細を提供します。このクラスのコンストラクタは、ユーザーに公開されていません。

performanceNodeTiming.bootstrapComplete#

Node.js プロセスがブートストラップを完了した高分解能ミリ秒タイムスタンプ。ブートストラップがまだ完了していない場合、プロパティの値は -1 です。

performanceNodeTiming.environment#

Node.js 環境が初期化された高分解能ミリ秒タイムスタンプ。

performanceNodeTiming.idleTime#

イベントループがイベントループのイベントプロバイダー (例: epoll_wait) 内でアイドル状態であった時間の高分解能ミリ秒タイムスタンプ。これは CPU 使用率を考慮しません。イベントループがまだ開始していない場合 (例: メインスクリプトの最初のティック)、プロパティの値は 0 です。

performanceNodeTiming.loopExit#

Node.js イベントループが終了した高分解能ミリ秒タイムスタンプ。イベントループがまだ終了していない場合、プロパティの値は -1 です。'exit' イベントのハンドラ内でのみ -1 以外の値を持つことができます。

performanceNodeTiming.loopStart#

Node.js イベントループが開始した高分解能ミリ秒タイムスタンプ。イベントループがまだ開始していない場合 (例: メインスクリプトの最初のティック)、プロパティの値は -1 です。

performanceNodeTiming.nodeStart#

Node.js プロセスが初期化された高分解能ミリ秒タイムスタンプ。

performanceNodeTiming.uvMetricsInfo#

  • 戻り値: <Object>
    • loopCount <number> イベントループの反復回数。
    • events <number> イベントハンドラによって処理されたイベントの数。
    • eventsWaiting <number> イベントプロバイダが呼び出されたときに処理を待っていたイベントの数。

これは uv_metrics_info 関数へのラッパーです。現在のイベントループメトリクスのセットを返します。

現在のループ反復中にスケジュールされたすべての操作が完了する前にメトリクスを収集することを避けるため、setImmediate を使用して実行がスケジュールされた関数内でこのプロパティを使用することをお勧めします。

const { performance } = require('node:perf_hooks');

setImmediate(() => {
  console.log(performance.nodeTiming.uvMetricsInfo);
});import { performance } from 'node:perf_hooks';

setImmediate(() => {
  console.log(performance.nodeTiming.uvMetricsInfo);
});

performanceNodeTiming.v8Start#

V8 プラットフォームが初期化された高分解能ミリ秒タイムスタンプ。

クラス: PerformanceResourceTiming#

アプリケーションのリソースの読み込みに関する詳細なネットワークタイミングデータを提供します。

このクラスのコンストラクタは、ユーザーに直接公開されていません。

performanceResourceTiming.workerStart#

fetch リクエストをディスパッチする直前の高分解能ミリ秒タイムスタンプ。リソースがワーカーによってインターセプトされない場合、このプロパティは常に 0 を返します。

performanceResourceTiming.redirectStart#

リダイレクトを開始する fetch の開始時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.redirectEnd#

最後のリダイレクトのレスポンスの最後のバイトを受信した直後に作成される高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.fetchStart#

Node.js がリソースのフェッチを開始する直前の高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.domainLookupStart#

Node.js がリソースのドメイン名検索を開始する直前の高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.domainLookupEnd#

Node.js がリソースのドメイン名検索を完了した直後の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.connectStart#

Node.js がリソースを取得するためにサーバーへの接続を確立し始める直前の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.connectEnd#

Node.js がリソースを取得するためにサーバーへの接続を確立し終えた直後の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.secureConnectionStart#

Node.js が現在の接続を保護するためにハンドシェイクプロセスを開始する直前の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.requestStart#

Node.js がサーバーからレスポンスの最初のバイトを受信する直前の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.responseEnd#

Node.js がリソースの最後のバイトを受信した直後、またはトランスポート接続が閉じる直前の、いずれか早い方の時刻を表す高分解能ミリ秒タイムスタンプ。

performanceResourceTiming.transferSize#

フェッチされたリソースのサイズ (オクテット単位) を表す数値。サイズには、レスポンスヘッダーフィールドとレスポンスペイロードボディが含まれます。

performanceResourceTiming.encodedBodySize#

フェッチ (HTTP またはキャッシュ) から受信したペイロードボディのサイズ (オクテット単位) を表す数値。適用されたコンテンツエンコーディングを削除する前の値です。

performanceResourceTiming.decodedBodySize#

フェッチ (HTTP またはキャッシュ) から受信したメッセージボディのサイズ (オクテット単位) を表す数値。適用されたコンテンツエンコーディングを削除した後の値です。

performanceResourceTiming.toJSON()#

PerformanceResourceTiming オブジェクトの JSON 表現である object を返します。

クラス: PerformanceObserver#

PerformanceObserver.supportedEntryTypes#

サポートされているタイプを取得します。

new PerformanceObserver(callback)#

PerformanceObserver オブジェクトは、新しい PerformanceEntry インスタンスがパフォーマンスタイムラインに追加されたときに通知を提供します。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries());

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['mark'], buffered: true });

performance.mark('test');const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries());

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['mark'], buffered: true });

performance.mark('test');

PerformanceObserver インスタンスは追加のパフォーマンスオーバーヘッドを発生させるため、インスタンスを無期限に通知にサブスクライブしたままにしないでください。ユーザーは、不要になったらすぐにオブザーバーを切断する必要があります。

callback は、PerformanceObserver が新しい PerformanceEntry インスタンスについて通知されたときに呼び出されます。コールバックは、PerformanceObserverEntryList インスタンスと PerformanceObserver への参照を受け取ります。

performanceObserver.disconnect()#

PerformanceObserver インスタンスをすべての通知から切断します。

performanceObserver.observe(options)#

  • options <Object>
    • type <string> 単一の <PerformanceEntry> タイプ。entryTypes がすでに指定されている場合は指定してはいけません。
    • entryTypes <string[]> オブザーバーが関心を持つ <PerformanceEntry> インスタンスのタイプを識別する文字列の配列。指定されていない場合、エラーがスローされます。
    • buffered <boolean> true の場合、オブザーバーコールバックはグローバルな PerformanceEntry バッファリングエントリのリストとともに呼び出されます。false の場合、その時点以降に作成された PerformanceEntry のみがオブザーバーコールバックに送信されます。デフォルト: false

<PerformanceObserver> インスタンスを、options.entryTypes または options.type のいずれかで識別される新しい <PerformanceEntry> インスタンスの通知にサブスクライブします。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((list, observer) => {
  // Called once asynchronously. `list` contains three items.
});
obs.observe({ type: 'mark' });

for (let n = 0; n < 3; n++)
  performance.mark(`test${n}`);const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const obs = new PerformanceObserver((list, observer) => {
  // Called once asynchronously. `list` contains three items.
});
obs.observe({ type: 'mark' });

for (let n = 0; n < 3; n++)
  performance.mark(`test${n}`);

performanceObserver.takeRecords()#

  • 戻り値: <PerformanceEntry[]> パフォーマンスオブザーバーに保存されている現在のエントリのリスト。リストは空になります。

クラス: PerformanceObserverEntryList#

PerformanceObserverEntryList クラスは、PerformanceObserver に渡された PerformanceEntry インスタンスへのアクセスを提供するために使用されます。このクラスのコンストラクタは、ユーザーに公開されていません。

performanceObserverEntryList.getEntries()#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntries());
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 81.465639,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 81.860064,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ type: 'mark' });

performance.mark('test');
performance.mark('meow');const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntries());
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 81.465639,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 81.860064,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ type: 'mark' });

performance.mark('test');
performance.mark('meow');

performanceObserverEntryList.getEntriesByName(name[, type])#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.namename と等しく、オプションで performanceEntry.entryTypetype と等しいエントリが含まれます。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntriesByName('meow'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 98.545991,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  console.log(perfObserverList.getEntriesByName('nope')); // []

  console.log(perfObserverList.getEntriesByName('test', 'mark'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 63.518931,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  console.log(perfObserverList.getEntriesByName('test', 'measure')); // []

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['mark', 'measure'] });

performance.mark('test');
performance.mark('meow');const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntriesByName('meow'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 98.545991,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  console.log(perfObserverList.getEntriesByName('nope')); // []

  console.log(perfObserverList.getEntriesByName('test', 'mark'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 63.518931,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  console.log(perfObserverList.getEntriesByName('test', 'measure')); // []

  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['mark', 'measure'] });

performance.mark('test');
performance.mark('meow');

performanceObserverEntryList.getEntriesByType(type)#

performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.entryTypetype と等しいエントリが含まれます。

import { performance, PerformanceObserver } from 'node:perf_hooks';

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntriesByType('mark'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 55.897834,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 56.350146,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ type: 'mark' });

performance.mark('test');
performance.mark('meow');const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const obs = new PerformanceObserver((perfObserverList, observer) => {
  console.log(perfObserverList.getEntriesByType('mark'));
  /**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 55.897834,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 56.350146,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */
  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ type: 'mark' });

performance.mark('test');
performance.mark('meow');

perf_hooks.createHistogram([options])#

  • options <Object>
    • lowest <number> | <bigint> 最も低い識別可能な値。0より大きい整数値でなければなりません。デフォルト: 1
    • highest <number> | <bigint> 最も高い記録可能な値。lowest の2倍以上の整数値でなければなりません。デフォルト: Number.MAX_SAFE_INTEGER
    • figures <number> 精度の桁数。1 から 5 までの数値でなければなりません。デフォルト: 3
  • 戻り値: <RecordableHistogram>

<RecordableHistogram> を返します。

perf_hooks.monitorEventLoopDelay([options])#

  • options <Object>
    • resolution <number> サンプリングレート (ミリ秒単位)。ゼロより大きくなければなりません。デフォルト: 10
  • 戻り値: <IntervalHistogram>

このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。

イベントループの遅延を経時的にサンプリングして報告する IntervalHistogram オブジェクトを作成します。遅延はナノ秒単位で報告されます。

タイマーを使用してイベントループのおおよその遅延を検出する方法が機能するのは、タイマーの実行が libuv イベントループのライフサイクルに特異的に結びついているためです。つまり、ループの遅延はタイマーの実行の遅延を引き起こし、この API は特にそのような遅延を検出することを目的としています。

import { monitorEventLoopDelay } from 'node:perf_hooks';

const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));const { monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));

クラス: Histogram#

histogram.count#

ヒストグラムによって記録されたサンプル数。

histogram.countBigInt#

ヒストグラムによって記録されたサンプル数。

histogram.exceeds#

イベントループの遅延が最大1時間のイベントループ遅延しきい値を超えた回数。

histogram.exceedsBigInt#

イベントループの遅延が最大1時間のイベントループ遅延しきい値を超えた回数。

histogram.max#

記録された最大のイベントループ遅延。

histogram.maxBigInt#

記録された最大のイベントループ遅延。

histogram.mean#

記録されたイベントループ遅延の平均値。

histogram.min#

記録された最小のイベントループ遅延。

histogram.minBigInt#

記録された最小のイベントループ遅延。

histogram.percentile(percentile)#

  • percentile <number> (0, 100] の範囲のパーセンタイル値。
  • 戻り値: <number>

指定されたパーセンタイルの値を返します。

histogram.percentileBigInt(percentile)#

  • percentile <number> (0, 100] の範囲のパーセンタイル値。
  • 戻り値: <bigint>

指定されたパーセンタイルの値を返します。

histogram.percentiles#

累積されたパーセンタイル分布を詳述する Map オブジェクトを返します。

histogram.percentilesBigInt#

累積されたパーセンタイル分布を詳述する Map オブジェクトを返します。

histogram.reset()#

収集されたヒストグラムデータをリセットします。

histogram.stddev#

記録されたイベントループ遅延の標準偏差。

クラス: IntervalHistogram extends Histogram#

指定された間隔で定期的に更新される Histogram

histogram.disable()#

更新間隔タイマーを無効にします。タイマーが停止した場合は true を、すでに停止していた場合は false を返します。

histogram.enable()#

更新間隔タイマーを有効にします。タイマーが開始された場合は true を、すでに開始されていた場合は false を返します。

histogram[Symbol.dispose]()#

ヒストグラムが破棄されるときに更新間隔タイマーを無効にします。

const { monitorEventLoopDelay } = require('node:perf_hooks');
{
  using hist = monitorEventLoopDelay({ resolution: 20 });
  hist.enable();
  // The histogram will be disabled when the block is exited.
} 

IntervalHistogram のクローン作成#

<IntervalHistogram> インスタンスは <MessagePort> を介してクローン作成できます。受信側では、ヒストグラムは enable()disable() メソッドを実装しないプレーンな <Histogram> オブジェクトとしてクローンされます。

クラス: RecordableHistogram extends Histogram#

histogram.add(other)#

other からの値をこのヒストグラムに追加します。

histogram.record(val)#

histogram.recordDelta()#

前回の recordDelta() の呼び出しから経過した時間 (ナノ秒単位) を計算し、その量をヒストグラムに記録します。

#

非同期操作の実行時間を測定する#

以下の例では、Async Hooks と Performance API を使用して、Timeout 操作の実際の実行時間 (コールバックの実行にかかった時間を含む) を測定します。

import { createHook } from 'node:async_hooks';
import { performance, PerformanceObserver } from 'node:perf_hooks';

const set = new Set();
const hook = createHook({
  init(id, type) {
    if (type === 'Timeout') {
      performance.mark(`Timeout-${id}-Init`);
      set.add(id);
    }
  },
  destroy(id) {
    if (set.has(id)) {
      set.delete(id);
      performance.mark(`Timeout-${id}-Destroy`);
      performance.measure(`Timeout-${id}`,
                          `Timeout-${id}-Init`,
                          `Timeout-${id}-Destroy`);
    }
  },
});
hook.enable();

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries()[0]);
  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['measure'], buffered: true });

setTimeout(() => {}, 1000);'use strict';
const async_hooks = require('node:async_hooks');
const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');

const set = new Set();
const hook = async_hooks.createHook({
  init(id, type) {
    if (type === 'Timeout') {
      performance.mark(`Timeout-${id}-Init`);
      set.add(id);
    }
  },
  destroy(id) {
    if (set.has(id)) {
      set.delete(id);
      performance.mark(`Timeout-${id}-Destroy`);
      performance.measure(`Timeout-${id}`,
                          `Timeout-${id}-Init`,
                          `Timeout-${id}-Destroy`);
    }
  },
});
hook.enable();

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries()[0]);
  performance.clearMarks();
  performance.clearMeasures();
  observer.disconnect();
});
obs.observe({ entryTypes: ['measure'] });

setTimeout(() => {}, 1000);

依存関係のロードにかかる時間を測定する#

以下の例では、依存関係をロードするための require() 操作の実行時間を測定します。

import { performance, PerformanceObserver } from 'node:perf_hooks';

// Activate the observer
const obs = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach((entry) => {
    console.log(`import('${entry[0]}')`, entry.duration);
  });
  performance.clearMarks();
  performance.clearMeasures();
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'], buffered: true });

const timedImport = performance.timerify(async (module) => {
  return await import(module);
});

await timedImport('some-module');'use strict';
const {
  performance,
  PerformanceObserver,
} = require('node:perf_hooks');
const mod = require('node:module');

// Monkey patch the require function
mod.Module.prototype.require =
  performance.timerify(mod.Module.prototype.require);
require = performance.timerify(require);

// Activate the observer
const obs = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach((entry) => {
    console.log(`require('${entry[0]}')`, entry.duration);
  });
  performance.clearMarks();
  performance.clearMeasures();
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

require('some-module');

HTTP のラウンドトリップに1回かかる時間を測定する#

以下の例は、HTTP クライアント (OutgoingMessage) と HTTP リクエスト (IncomingMessage) によって費やされた時間を追跡するために使用されます。HTTP クライアントの場合、リクエストの開始からレスポンスの受信までの時間間隔を意味し、HTTP リクエストの場合、リクエストの受信からレスポンスの送信までの時間間隔を意味します。

import { PerformanceObserver } from 'node:perf_hooks';
import { createServer, get } from 'node:http';

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});

obs.observe({ entryTypes: ['http'] });

const PORT = 8080;

createServer((req, res) => {
  res.end('ok');
}).listen(PORT, () => {
  get(`http://127.0.0.1:${PORT}`);
});'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const http = require('node:http');

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});

obs.observe({ entryTypes: ['http'] });

const PORT = 8080;

http.createServer((req, res) => {
  res.end('ok');
}).listen(PORT, () => {
  http.get(`http://127.0.0.1:${PORT}`);
});

接続が成功した場合に net.connect (TCP のみ) にかかる時間を測定する#

import { PerformanceObserver } from 'node:perf_hooks';
import { connect, createServer } from 'node:net';

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});
obs.observe({ entryTypes: ['net'] });
const PORT = 8080;
createServer((socket) => {
  socket.destroy();
}).listen(PORT, () => {
  connect(PORT);
});'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const net = require('node:net');
const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});
obs.observe({ entryTypes: ['net'] });
const PORT = 8080;
net.createServer((socket) => {
  socket.destroy();
}).listen(PORT, () => {
  net.connect(PORT);
});

リクエストが成功した場合に DNS にかかる時間を測定する#

import { PerformanceObserver } from 'node:perf_hooks';
import { lookup, promises } from 'node:dns';

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});
obs.observe({ entryTypes: ['dns'] });
lookup('localhost', () => {});
promises.resolve('localhost');'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const dns = require('node:dns');
const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});
obs.observe({ entryTypes: ['dns'] });
dns.lookup('localhost', () => {});
dns.promises.resolve('localhost');