Node.js v21.7.2 ドキュメント
- Node.js v21.7.2
-
► 目次
- パフォーマンス測定API
perf_hooks.performance
performance.clearMarks([name])
performance.clearMeasures([name])
performance.clearResourceTimings([name])
performance.eventLoopUtilization([utilization1[, utilization2]])
performance.getEntries()
performance.getEntriesByName(name[, type])
performance.getEntriesByType(type)
performance.mark(name[, options])
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)
performance.measure(name[, startMarkOrOptions[, endMark]])
performance.nodeTiming
performance.now()
performance.setResourceTimingBufferSize(maxSize)
performance.timeOrigin
performance.timerify(fn[, options])
performance.toJSON()
- クラス: `PerformanceEntry`
- クラス: `PerformanceMark`
- クラス: `PerformanceMeasure`
- クラス: `PerformanceNodeEntry`
- クラス: `PerformanceNodeTiming`
- クラス: `PerformanceResourceTiming`
performanceResourceTiming.workerStart
performanceResourceTiming.redirectStart
performanceResourceTiming.redirectEnd
performanceResourceTiming.fetchStart
performanceResourceTiming.domainLookupStart
performanceResourceTiming.domainLookupEnd
performanceResourceTiming.connectStart
performanceResourceTiming.connectEnd
performanceResourceTiming.secureConnectionStart
performanceResourceTiming.requestStart
performanceResourceTiming.responseEnd
performanceResourceTiming.transferSize
performanceResourceTiming.encodedBodySize
performanceResourceTiming.decodedBodySize
performanceResourceTiming.toJSON()
- クラス: `PerformanceObserver`
- クラス: `PerformanceObserverEntryList`
perf_hooks.createHistogram([options])
perf_hooks.monitorEventLoopDelay([options])
- クラス: `Histogram`
histogram.count
histogram.countBigInt
histogram.exceeds
histogram.exceedsBigInt
histogram.max
histogram.maxBigInt
histogram.mean
histogram.min
histogram.minBigInt
histogram.percentile(percentile)
histogram.percentileBigInt(percentile)
histogram.percentiles
histogram.percentilesBigInt
histogram.reset()
histogram.stddev
- クラス: `IntervalHistogram extends Histogram`
- クラス: `RecordableHistogram extends Histogram`
- 例
- パフォーマンス測定API
-
► インデックス
- アサーションテスト
- 非同期コンテキスト追跡
- Async Hooks
- バッファ
- C++ アドオン
- Node-API を使用した C/C++ アドオン
- C++ エンベッダーAPI
- 子プロセス
- クラスタ
- コマンドラインオプション
- コンソール
- Corepack
- 暗号化
- デバッガ
- 非推奨API
- 診断チャネル
- DNS
- ドメイン
- エラー
- イベント
- ファイルシステム
- グローバルオブジェクト
- HTTP
- HTTP/2
- HTTPS
- インスペクタ
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール: `node:module` API
- モジュール: パッケージ
- ネットワーク
- OS
- パス
- パフォーマンスフック
- パーミッション
- プロセス
- Punnycode
- クエリ文字列
- Readline
- REPL
- レポート
- 単一実行可能アプリケーション
- ストリーム
- 文字列デコーダ
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/データグラム
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- ► その他のバージョン
- ► オプション
パフォーマンス測定API#
ソースコード: lib/perf_hooks.js
このモジュールは、W3CのWebパフォーマンスAPI のサブセットと、Node.js固有のパフォーマンス測定のための追加APIの実装を提供します。
Node.js は以下の Web パフォーマンス API をサポートしています。
const { PerformanceObserver, performance } = require('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');
});
perf_hooks.performance
#
現在のNode.jsインスタンスからパフォーマンスメトリックを収集するために使用できるオブジェクトです。ブラウザのwindow.performance
と似ています。
performance.clearMarks([name])
#
name
<文字列>
name
が指定されていない場合、パフォーマンスタイムラインからすべてのPerformanceMark
オブジェクトを削除します。name
が指定されている場合、名前付きのマークのみを削除します。
performance.clearMeasures([name])
#
name
<文字列>
name
が指定されていない場合、パフォーマンスタイムラインからすべてのPerformanceMeasure
オブジェクトを削除します。name
が指定されている場合、名前付きの測定値のみを削除します。
performance.clearResourceTimings([name])
#
name
<文字列>
name
が指定されていない場合、リソースタイムラインからすべてのPerformanceResourceTiming
オブジェクトを削除します。name
が指定されている場合、名前付きのリソースのみを削除します。
performance.eventLoopUtilization([utilization1[, utilization2]])
#
utilization1
<オブジェクト> 以前の`eventLoopUtilization()`呼び出しの結果。utilization2
<オブジェクト>utilization1
より前の`eventLoopUtilization()`呼び出しの結果。- 戻り値: <オブジェクト>
eventLoopUtilization()
メソッドは、イベントループがアイドル状態とアクティブ状態だった累積時間を高解像度ミリ秒タイマーとして含むオブジェクトを返します。utilization
値は、計算されたイベントループ使用率(ELU)です。
メインスレッドでブートストラップがまだ完了していない場合、プロパティの値は0
になります。ブートストラップはイベントループ内で行われるため、ELUはワーカースレッドではすぐに利用できます。
utilization1
とutilization2
の両方はオプションパラメータです。
utilization1
が渡された場合、現在の呼び出しのactive
時間とidle
時間の間の差、および対応するutilization
値が計算されて返されます(process.hrtime()
と同様です)。
utilization1
とutilization2
の両方が渡された場合、2つの引数の間の差が計算されます。これは便利なオプションです。なぜなら、process.hrtime()
とは異なり、ELUの計算は単一の減算よりも複雑だからです。
ELUはCPU使用率に似ていますが、CPU使用率ではなくイベントループ統計のみを測定します。これは、イベントループがイベントループのイベントプロバイダ(例:`epoll_wait`)の外で過ごした時間の割合を表しています。その他のCPUアイドル時間は考慮されません。ほとんどアイドル状態のプロセスではELUが高くなる例を以下に示します。
'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[]>
performanceEntry.startTime
に関して時系列順に並べられたPerformanceEntry
オブジェクトのリストを返します。特定のタイプのパフォーマンスエントリ、または特定の名前を持つパフォーマンスエントリのみに関心がある場合は、performance.getEntriesByType()
とperformance.getEntriesByName()
を参照してください。
performance.getEntriesByName(name[, type])
#
name
<文字列>type
<string>- 返り値: <PerformanceEntry[]>
performanceEntry.name
がname
と等しく、オプションでperformanceEntry.entryType
がtype
と等しいPerformanceEntry
オブジェクトのリストを、performanceEntry.startTime
に関して時系列順に返します。
performance.getEntriesByType(type)
#
type
<string>- 返り値: <PerformanceEntry[]>
performanceEntry.entryType
がtype
と等しいPerformanceEntry
オブジェクトのリストを、performanceEntry.startTime
に関して時系列順に返します。
performance.mark(name[, options])
#
パフォーマンスタイムラインに新しいPerformanceMark
エントリを作成します。PerformanceMark
はPerformanceEntry
のサブクラスであり、そのperformanceEntry.entryType
は常に'mark'
で、performanceEntry.duration
は常に0
です。パフォーマンスマークは、パフォーマンスタイムラインにおける特定の重要な瞬間をマークするために使用されます。
作成されたPerformanceMark
エントリはグローバルパフォーマンスタイムラインに配置され、performance.getEntries
、performance.getEntriesByName
、performance.getEntriesByType
を使用してクエリできます。観測が実行されたら、performance.clearMarks
を使用してグローバルパフォーマンスタイムラインからエントリを手動でクリアする必要があります。
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)
#
timingInfo
<Object> Fetch Timing InforequestedUrl
<string> リソースURLinitiatorType
<string> イニシエータ名(例: 'fetch')global
<Object>cacheMode
<string> キャッシュモードは空文字列('')または'local'でなければなりません。
このプロパティはNode.jsによる拡張です。Webブラウザでは使用できません。
リソースタイムラインに新しいPerformanceResourceTiming
エントリを作成します。PerformanceResourceTiming
はPerformanceEntry
のサブクラスであり、そのperformanceEntry.entryType
は常に'resource'
です。パフォーマンスリソースは、リソースタイムラインにおける瞬間をマークするために使用されます。
作成されたPerformanceMark
エントリはグローバルリソースタイムラインに配置され、performance.getEntries
、performance.getEntriesByName
、performance.getEntriesByType
を使用してクエリできます。観測が実行されたら、performance.clearResourceTimings
を使用してグローバルパフォーマンスタイムラインからエントリを手動でクリアする必要があります。
performance.measure(name[, startMarkOrOptions[, endMark]])
#
name
<文字列>startMarkOrOptions
<string> | <Object> オプション。endMark
<string> オプション。startMarkOrOptions
が<Object>の場合は省略する必要があります。
パフォーマンスタイムラインに新しいPerformanceMeasure
エントリを作成します。PerformanceMeasure
はPerformanceEntry
のサブクラスであり、そのperformanceEntry.entryType
は常に'measure'
で、performanceEntry.duration
はstartMark
とendMark
の経過ミリ秒数を測定します。
startMark
引数は、パフォーマンスタイムラインにある既存のPerformanceMark
を識別するか、PerformanceNodeTiming
クラスによって提供されるタイムスタンププロパティのいずれかを識別できます。指定されたstartMark
が存在しない場合、エラーがスローされます。
オプションのendMark
引数は、パフォーマンスタイムラインにある既存のPerformanceMark
またはPerformanceNodeTiming
クラスによって提供されるタイムスタンププロパティのいずれかを識別する必要があります。パラメータが渡されない場合、endMark
はperformance.now()
になります。そうでない場合、指定されたendMark
が存在しない場合、エラーがスローされます。
作成されたPerformanceMeasure
エントリはグローバルパフォーマンスタイムラインに配置され、performance.getEntries
、performance.getEntriesByName
、performance.getEntriesByType
を使用してクエリできます。観測が実行されたら、performance.clearMeasures
を使用してグローバルパフォーマンスタイムラインからエントリを手動でクリアする必要があります。
performance.nodeTiming
#
このプロパティはNode.jsによる拡張です。Webブラウザでは使用できません。
特定のNode.js運用上のマイルストーンのパフォーマンスメトリクスを提供するPerformanceNodeTiming
クラスのインスタンス。
performance.now()
#
- 返り値: <number>
現在の高解像度ミリ秒タイムスタンプを返します。ここで、0は現在のnode
プロセスの開始を表します。
performance.setResourceTimingBufferSize(maxSize)
#
グローバルパフォーマンスリソースタイミングバッファサイズを、指定された数の「resource」タイプのperformanceエントリオブジェクトに設定します。
デフォルトでは、最大バッファサイズは250に設定されています。
performance.timeOrigin
#
timeOrigin
は、Unix時間で測定された、現在のnode
プロセスが開始された高解像度ミリ秒タイムスタンプを指定します。
performance.timerify(fn[, options])
#
fn
<Function>options
<Object>histogram
<RecordableHistogram>perf_hooks.createHistogram()
を使用して作成されたヒストグラムオブジェクトで、実行時間のナノ秒単位の記録を行います。
このプロパティはNode.jsによる拡張です。Webブラウザでは使用できません。
ラップされた関数の実行時間を測定する新しい関数内に関数をラップします。タイミングの詳細にアクセスするには、PerformanceObserver
を'function'
イベントタイプに購読する必要があります。
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();
ラップされた関数がPromiseを返す場合、finallyハンドラがPromiseに添付され、finallyハンドラが呼び出されると期間が報告されます。
performance.toJSON()
#
performance
オブジェクトのJSON表現であるオブジェクト。ブラウザのwindow.performance.toJSON
に似ています。
イベント: 'resourcetimingbufferfull'
#
グローバルパフォーマンスリソースタイミングバッファがいっぱいになると、'resourcetimingbufferfull'
イベントが発生します。イベントリスナーでperformance.setResourceTimingBufferSize()
を使用してリソースタイミングバッファサイズを調整するか、performance.clearResourceTimings()
を使用してバッファをクリアして、パフォーマンスタイムラインバッファにさらにエントリを追加できるようにします。
クラス: PerformanceEntry
#
このクラスのコンストラクタは、ユーザーには直接公開されていません。
performanceEntry.duration
#
このエントリ経過した総ミリ秒数。この値は、すべてのパフォーマンスエントリタイプで意味のある値とは限りません。
performanceEntry.entryType
#
パフォーマンスエントリのタイプ。次のいずれかになります。
'node'
(Node.jsのみ)'mark'
(Webで使用可能)'measure'
(Webで使用可能)'gc'
(Node.jsのみ)'function'
(Node.jsのみ)'http2'
(Node.jsのみ)'http'
(Node.jsのみ)
performanceEntry.name
#
パフォーマンスエントリの名称。
performanceEntry.startTime
#
パフォーマンスエントリの開始時刻を示す、高解像度のミリ秒単位のタイムスタンプ。
クラス: PerformanceMark
#
- 継承元: <PerformanceEntry>
Performance.mark()
メソッドで作成されたマークを公開します。
performanceMark.detail
#
Performance.mark()
メソッドで作成時に指定された追加の詳細情報。
クラス: PerformanceMeasure
#
- 継承元: <PerformanceEntry>
Performance.measure()
メソッドで作成された測定値を公開します。
このクラスのコンストラクタは、ユーザーには直接公開されていません。
performanceMeasure.detail
#
Performance.measure()
メソッドで作成時に指定された追加の詳細情報。
クラス: PerformanceNodeEntry
#
- 継承元: <PerformanceEntry>
このクラスはNode.jsによる拡張です。Webブラウザでは使用できません。
Node.jsのタイミングに関する詳細なデータを提供します。
このクラスのコンストラクタは、ユーザーには直接公開されていません。
performanceNodeEntry.detail
#
entryType
に固有の追加の詳細情報。
performanceNodeEntry.flags
#
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
#
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.name
がHttpClient
の場合、detail
にはreq
、res
のプロパティが含まれます。req
プロパティはmethod
、url
、headers
を含む<Object>、res
プロパティはstatusCode
、statusMessage
、headers
を含む<Object>になります。
performanceEntry.name
がHttpRequest
の場合、detail
にはreq
、res
のプロパティが含まれます。req
プロパティはmethod
、url
、headers
を含む<Object>、res
プロパティはstatusCode
、statusMessage
、headers
を含む<Object>になります。
これにより追加のメモリオーバーヘッドが発生する可能性があるため、診断目的でのみ使用し、デフォルトで本番環境で有効にしておくべきではありません。
HTTP/2 ('http2')の詳細#
performanceEntry.type
が'http2'
の場合、performanceNodeEntry.detail
プロパティは追加のパフォーマンス情報を含む<Object>になります。
performanceEntry.name
がHttp2Stream
の場合、detail
には次のプロパティが含まれます。
bytesRead
<number> このHttp2Stream
で受信したDATA
フレームバイト数。bytesWritten
<number> このHttp2Stream
で送信したDATA
フレームバイト数。id
<number> 関連付けられたHttp2Stream
の識別子。timeToFirstByte
<number>PerformanceEntry
のstartTime
と最初のDATA
フレームの受信との間の経過ミリ秒数。timeToFirstByteSent
<number>PerformanceEntry
のstartTime
と最初のDATA
フレームの送信との間の経過ミリ秒数。timeToFirstHeader
<number>PerformanceEntry
のstartTime
と最初のヘッダーの受信との間の経過ミリ秒数。
performanceEntry.name
がHttp2Session
の場合、detail
には次のプロパティが含まれます。
bytesRead
<number> このHttp2Session
で受信したバイト数。bytesWritten
<number> このHttp2Session
で送信したバイト数。framesReceived
<number>Http2Session
によって受信されたHTTP/2フレーム数。framesSent
<number>Http2Session
によって送信されたHTTP/2フレーム数。maxConcurrentStreams
<number>Http2Session
のライフタイム中に同時に開かれたストリームの最大数。pingRTT
<number>PING
フレームの送信と確認応答の受信との間の経過ミリ秒数。PING
フレームがHttp2Session
で送信された場合にのみ存在します。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.name
がconnect
の場合、detail
にはhost
、port
のプロパティが含まれます。
DNS ('dns')の詳細#
performanceEntry.type
が'dns'
の場合、performanceNodeEntry.detail
プロパティは追加情報を含む<Object>になります。
performanceEntry.name
がlookup
の場合、detail
にはhostname
、family
、hints
、verbatim
、addresses
のプロパティが含まれます。
performanceEntry.name
がlookupService
の場合、detail
にはhost
、port
、hostname
、service
のプロパティが含まれます。
performanceEntry.name
がqueryxxx
またはgetHostByAddr
の場合、detail
にはhost
、ttl
、result
のプロパティが含まれます。result
の値はqueryxxx
またはgetHostByAddr
の結果と同じです。
クラス: PerformanceNodeTiming
#
- 継承元: <PerformanceEntry>
このプロパティは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.v8Start
#
V8 プラットフォームが初期化された時点の高解像度ミリ秒単位のタイムスタンプです。
クラス: PerformanceResourceTiming
#
- 継承元: <PerformanceEntry>
アプリケーションのリソースの読み込みに関する詳細なネットワークタイミングデータを提供します。
このクラスのコンストラクタは、ユーザーには直接公開されていません。
performanceResourceTiming.workerStart
#
fetch
リクエストのディスパッチの直前の高解像度ミリ秒単位のタイムスタンプです。リソースがワーカーによってインターセプトされない場合、プロパティは常に 0 を返します。
performanceResourceTiming.redirectStart
#
リダイレクトを開始するフェッチの開始時間を表す高解像度ミリ秒単位のタイムスタンプです。
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)
#
callback
<Function>list
<PerformanceObserverEntryList>observer
<PerformanceObserver>
PerformanceObserver
オブジェクトは、新しいPerformanceEntry
インスタンスがパフォーマンスタイムラインに追加されたときに通知を提供します。
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
インスタンスは独自の追加のパフォーマンスオーバーヘッドを導入するため、インスタンスを無期限に通知に購読したままにしておくべきではありません。ユーザーは、必要なくなった時点でオブザーバーの接続を解除する必要があります。
新しいPerformanceEntry
インスタンスについてPerformanceObserver
が通知されると、callback
が呼び出されます。コールバックは、PerformanceObserverEntryList
インスタンスとPerformanceObserver
への参照を受け取ります。
performanceObserver.disconnect()
#
PerformanceObserver
インスタンスをすべての通知から切断します。
performanceObserver.observe(options)
#
options
<Object>type
<string> 単一の<PerformanceEntry>タイプ。entryTypes
が既に指定されている場合は指定しないでください。entryTypes
<string[]>オブザーバーが関心のある<PerformanceEntry>インスタンスのタイプを識別する文字列の配列です。指定されていない場合、エラーがスローされます。buffered
<boolean> trueの場合、オブザーバーコールバックはグローバルなPerformanceEntry
のバッファリングされたエントリのリストで呼び出されます。falseの場合、時点以降に作成されたPerformanceEntry
のみがオブザーバーコールバックに送信されます。**デフォルト:**false
。
options.entryTypes
またはoptions.type
によって識別される新しい<PerformanceEntry>インスタンスの通知に<PerformanceObserver>インスタンスをサブスクライブします。
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}`);
クラス: PerformanceObserverEntryList
#
PerformanceObserverEntryList
クラスは、PerformanceObserver
に渡されたPerformanceEntry
インスタンスへのアクセスを提供するために使用されます。このクラスのコンストラクターはユーザーには公開されていません。
performanceObserverEntryList.getEntries()
#
- 返り値: <PerformanceEntry[]>
performanceEntry.startTime
に関して時系列順に並べられたPerformanceEntry
オブジェクトのリストを返します。
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])
#
name
<文字列>type
<string>- 返り値: <PerformanceEntry[]>
performanceEntry.name
がname
と等しく、オプションでperformanceEntry.entryType
がtype
と等しいPerformanceEntry
オブジェクトのリストを、performanceEntry.startTime
に関して時系列順に返します。
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)
#
type
<string>- 返り値: <PerformanceEntry[]>
performanceEntry.entryType
がtype
と等しいPerformanceEntry
オブジェクトのリストを、performanceEntry.startTime
に関して時系列順に返します。
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>- 戻り値: <RecordableHistogram>
<RecordableHistogram>を返します。
perf_hooks.monitorEventLoopDelay([options])
#
options
<Object>resolution
<number> サンプリングレート(ミリ秒単位)。0より大きい値である必要があります。デフォルト:10
。
- 戻り値: <IntervalHistogram>
このプロパティはNode.jsによる拡張です。Webブラウザでは使用できません。
時間経過に伴うイベントループの遅延をサンプリングして報告するIntervalHistogram
オブジェクトを作成します。遅延はナノ秒単位で報告されます。
タイマーを使用してイベントループの遅延を概算で検出できるのは、タイマーの実行がlibuvイベントループのライフサイクルに特化して結びついているためです。つまり、ループの遅延はタイマーの実行の遅延を引き起こし、これらの遅延は、このAPIが検出することを意図したものです。
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)
#
指定されたパーセンタイルの値を返します。
histogram.percentileBigInt(percentile)
#
指定されたパーセンタイルの値を返します。
histogram.percentiles
#
累積パーセンタイル分布の詳細を示すMap
オブジェクトを返します。
histogram.percentilesBigInt
#
累積パーセンタイル分布の詳細を示すMap
オブジェクトを返します。
histogram.reset()
#
収集されたヒストグラムデータをリセットします。
histogram.stddev
#
記録されたイベントループ遅延の標準偏差。
クラス: IntervalHistogram extends Histogram
#
指定された間隔で定期的に更新されるHistogram
。
histogram.disable()
#
- 戻り値: <boolean>
更新間隔タイマーを無効にします。タイマーが停止された場合はtrue
、既に停止されていた場合はfalse
を返します。
histogram.enable()
#
- 戻り値: <boolean>
更新間隔タイマーを有効にします。タイマーが開始された場合はtrue
、既に開始されていた場合はfalse
を返します。
IntervalHistogram
の複製#
<IntervalHistogram>インスタンスは<MessagePort>を介して複製できます。受信側では、ヒストグラムはenable()
メソッドとdisable()
メソッドを実装しないプレーンな<Histogram>オブジェクトとして複製されます。
クラス: RecordableHistogram extends Histogram
#
histogram.add(other)
#
other
<RecordableHistogram>
other
の値をこのヒストグラムに追加します。
histogram.record(val)
#
histogram.recordDelta()
#
recordDelta()
への前回呼び出し以降に経過した時間(ナノ秒単位)を計算し、その量をヒストグラムに記録します。
例#
非同期操作の持続時間の測定#
次の例では、非同期フックとパフォーマンスAPIを使用して、タイムアウト操作の実際の持続時間(コールバックの実行にかかった時間を含む)を測定します。
'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'], buffered: true });
setTimeout(() => {}, 1000);
依存関係のロードにかかる時間の測定#
次の例では、依存関係をロードするためのrequire()
操作の持続時間を測定します。
'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'], buffered: true });
require('some-module');
1回のHTTPラウンドトリップにかかる時間の測定#
次の例は、HTTPクライアント(OutgoingMessage
)とHTTPリクエスト(IncomingMessage
)によって費やされた時間を追跡するために使用されます。HTTPクライアントの場合、リクエストの開始とレスポンスの受信の間の時間間隔を意味し、HTTPリクエストの場合、リクエストの受信とレスポンスの送信の間の時間間隔を意味します。
'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のみ)にかかる時間の測定#
'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にかかる時間の測定#
'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');