Node.js v25.0.0 ドキュメンテーション
- Node.js v25.0.0
-
目次
- パフォーマンス計測 API
perf_hooks.performanceperformance.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, bodyInfo, responseStatus[, deliveryType])performance.measure(name[, startMarkOrOptions[, endMark]])performance.nodeTimingperformance.now()performance.setResourceTimingBufferSize(maxSize)performance.timeOriginperformance.timerify(fn[, options])performance.toJSON()
- クラス:
PerformanceEntry - クラス:
PerformanceMark - クラス:
PerformanceMeasure - クラス:
PerformanceNodeEntry - クラス:
PerformanceNodeTiming - クラス:
PerformanceResourceTimingperformanceResourceTiming.workerStartperformanceResourceTiming.redirectStartperformanceResourceTiming.redirectEndperformanceResourceTiming.fetchStartperformanceResourceTiming.domainLookupStartperformanceResourceTiming.domainLookupEndperformanceResourceTiming.connectStartperformanceResourceTiming.connectEndperformanceResourceTiming.secureConnectionStartperformanceResourceTiming.requestStartperformanceResourceTiming.responseEndperformanceResourceTiming.transferSizeperformanceResourceTiming.encodedBodySizeperformanceResourceTiming.decodedBodySizeperformanceResourceTiming.toJSON()
- クラス:
PerformanceObserver - クラス:
PerformanceObserverEntryList perf_hooks.createHistogram([options])perf_hooks.monitorEventLoopDelay([options])- クラス:
Histogramhistogram.counthistogram.countBigInthistogram.exceedshistogram.exceedsBigInthistogram.maxhistogram.maxBigInthistogram.meanhistogram.minhistogram.minBigInthistogram.percentile(percentile)histogram.percentileBigInt(percentile)histogram.percentileshistogram.percentilesBigInthistogram.reset()histogram.stddev
- クラス:
IntervalHistogram extends Histogram - クラス:
RecordableHistogram extends Histogram - 例
- パフォーマンス計測 API
-
索引
- アサーションテスト
- 非同期コンテキストの追跡
- Async hooks
- Buffer
- C++アドオン
- Node-API を使用した C/C++ アドオン
- C++ embedder API
- 子プロセス
- Cluster
- コマンドラインオプション
- Console
- Crypto
- Debugger
- 非推奨のAPI
- Diagnostics Channel
- DNS
- Domain
- 環境変数
- エラー
- Events
- ファイルシステム
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール:
node:moduleAPI - モジュール: パッケージ
- モジュール: TypeScript
- Net
- OS
- Path
- Performance hooks
- パーミッション
- Process
- Punycode
- クエリストリング
- Readline
- REPL
- レポート
- 単一実行可能ファイルアプリケーション
- SQLite
- Stream
- String decoder
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/datagram
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- 他のバージョン
- オプション
パフォーマンス計測 API#
ソースコード: lib/perf_hooks.js
このモジュールは、W3C Web Performance API のサブセットの実装と、Node.js 固有のパフォーマンス測定のための追加 API を提供します。
Node.js は、以下の Web Performance API をサポートしています。
- 高分解能時間 (High Resolution Time)
- パフォーマンスタイムライン (Performance Timeline)
- ユーザータイミング (User Timing)
- リソースタイミング (Resource Timing)
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<string>
name が指定されていない場合、パフォーマンスタイムラインからすべての PerformanceMark オブジェクトを削除します。name が指定されている場合、指定された名前のマークのみを削除します。
performance.clearMeasures([name])#
name<string>
name が指定されていない場合、パフォーマンスタイムラインからすべての PerformanceMeasure オブジェクトを削除します。name が指定されている場合、指定された名前のメジャーのみを削除します。
performance.clearResourceTimings([name])#
name<string>
name が指定されていない場合、リソースタイムラインからすべての PerformanceResourceTiming オブジェクトを削除します。name が指定されている場合、指定された名前のリソースのみを削除します。
performance.eventLoopUtilization([utilization1[, utilization2]])#
utilization1<Object> 以前のeventLoopUtilization()呼び出しの結果。utilization2<Object>utilization1より前のeventLoopUtilization()呼び出しの結果。- 戻り値: <Object>
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 を持つ例です。
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[]>
performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。特定のタイプまたは特定の名前のパフォーマンスエントリのみに関心がある場合は、performance.getEntriesByType() と performance.getEntriesByName() を参照してください。
performance.getEntriesByName(name[, type])#
name<string>type<string>- 戻り値: <PerformanceEntry[]>
performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.name が name と等しく、オプションで performanceEntry.entryType が type と等しいエントリが含まれます。
performance.getEntriesByType(type)#
type<string>- 戻り値: <PerformanceEntry[]>
performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.entryType が type と等しいエントリが含まれます。
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, bodyInfo, responseStatus[, deliveryType])#
timingInfo<Object> Fetch タイミング情報requestedUrl<string> リソース URLinitiatorType<string> イニシエータ名、例: 'fetch'global<Object>cacheMode<string> キャッシュモードは空文字列 ('') または 'local' でなければなりませんbodyInfo<Object> Fetch レスポンスボディ情報responseStatus<number> レスポンスのステータスコードdeliveryType<string> 配信タイプ。デフォルト:''。
このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。
リソースタイムラインに新しい PerformanceResourceTiming エントリを作成します。PerformanceResourceTiming は PerformanceEntry のサブクラスで、performanceEntry.entryType は常に 'resource' です。パフォーマンスリソースは、リソースタイムライン上の瞬間をマークするために使用されます。
作成された PerformanceMark エントリは、グローバルリソースタイムラインに配置され、performance.getEntries、performance.getEntriesByName、performance.getEntriesByType を使ってクエリできます。観測が実行されたら、エントリは performance.clearResourceTimings を使ってグローバルパフォーマンスタイムラインから手動でクリアする必要があります。
performance.measure(name[, startMarkOrOptions[, endMark]])#
name<string>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.setResourceTimingBufferSize(maxSize)#
グローバルなパフォーマンスリソースタイミングバッファのサイズを、指定された数の "resource" タイプのパフォーマンスエントリオブジェクトに設定します。
デフォルトでは、最大バッファサイズは 250 に設定されています。
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#
- 型: <number>
このエントリに対して経過した合計ミリ秒数。この値は、すべての Performance Entry タイプで意味があるわけではありません。
クラス: PerformanceMark#
Performance.mark() メソッドを介して作成されたマークを公開します。
クラス: PerformanceMeasure#
Performance.measure() メソッドを介して作成されたメジャーを公開します。
このクラスのコンストラクタは、ユーザーに直接公開されていません。
クラス: PerformanceNodeEntry#
このクラスは Node.js による拡張です。Web ブラウザでは利用できません。
詳細な Node.js タイミングデータを提供します。
このクラスのコンストラクタは、ユーザーに直接公開されていません。
performanceNodeEntry.flags#
performanceNodeEntry.detail を使用してください。- 型: <number>
performanceEntry.entryType が 'gc' の場合、performance.flags プロパティにはガベージコレクション操作に関する追加情報が含まれます。値は以下のいずれかです。
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
performanceNodeEntry.kind#
performanceNodeEntry.detail を使用してください。- 型: <number>
performanceEntry.entryType が 'gc' の場合、performance.kind プロパティは発生したガベージコレクション操作のタイプを識別します。値は以下のいずれかです。
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
ガベージコレクション ('gc') の詳細#
performanceEntry.type が 'gc' の場合、performanceNodeEntry.detail プロパティは2つのプロパティを持つ <Object> になります。
kind<number> 以下のいずれかです。perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
flags<number> 以下のいずれかです。perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_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フレームの送信とその確認応答の受信との間に経過したミリ秒数。Http2SessionでPINGフレームが送信された場合にのみ存在します。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#
このプロパティは Node.js による拡張です。Web ブラウザでは利用できません。
Node.js 自体のタイミング詳細を提供します。このクラスのコンストラクタは、ユーザーに公開されていません。
performanceNodeTiming.bootstrapComplete#
- 型: <number>
Node.js プロセスがブートストラップを完了した高分解能ミリ秒タイムスタンプ。ブートストラップがまだ完了していない場合、プロパティの値は -1 です。
performanceNodeTiming.idleTime#
- 型: <number>
イベントループがイベントループのイベントプロバイダー (例: epoll_wait) 内でアイドル状態であった時間の高分解能ミリ秒タイムスタンプ。これは CPU 使用率を考慮しません。イベントループがまだ開始していない場合 (例: メインスクリプトの最初のティック)、プロパティの値は 0 です。
performanceNodeTiming.loopExit#
- 型: <number>
Node.js イベントループが終了した高分解能ミリ秒タイムスタンプ。イベントループがまだ終了していない場合、プロパティの値は -1 です。'exit' イベントのハンドラ内でのみ -1 以外の値を持つことができます。
performanceNodeTiming.loopStart#
- 型: <number>
Node.js イベントループが開始した高分解能ミリ秒タイムスタンプ。イベントループがまだ開始していない場合 (例: メインスクリプトの最初のティック)、プロパティの値は -1 です。
performanceNodeTiming.uvMetricsInfo#
- 戻り値: <Object>
これは 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);
});
クラス: PerformanceResourceTiming#
アプリケーションのリソースの読み込みに関する詳細なネットワークタイミングデータを提供します。
このクラスのコンストラクタは、ユーザーに直接公開されていません。
performanceResourceTiming.workerStart#
- 型: <number>
fetch リクエストをディスパッチする直前の高分解能ミリ秒タイムスタンプ。リソースがワーカーによってインターセプトされない場合、このプロパティは常に 0 を返します。
performanceResourceTiming.redirectEnd#
- 型: <number>
最後のリダイレクトのレスポンスの最後のバイトを受信した直後に作成される高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.domainLookupStart#
- 型: <number>
Node.js がリソースのドメイン名検索を開始する直前の高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.domainLookupEnd#
- 型: <number>
Node.js がリソースのドメイン名検索を完了した直後の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.connectStart#
- 型: <number>
Node.js がリソースを取得するためにサーバーへの接続を確立し始める直前の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.connectEnd#
- 型: <number>
Node.js がリソースを取得するためにサーバーへの接続を確立し終えた直後の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.secureConnectionStart#
- 型: <number>
Node.js が現在の接続を保護するためにハンドシェイクプロセスを開始する直前の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.requestStart#
- 型: <number>
Node.js がサーバーからレスポンスの最初のバイトを受信する直前の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.responseEnd#
- 型: <number>
Node.js がリソースの最後のバイトを受信した直後、またはトランスポート接続が閉じる直前の、いずれか早い方の時刻を表す高分解能ミリ秒タイムスタンプ。
performanceResourceTiming.transferSize#
- 型: <number>
フェッチされたリソースのサイズ (オクテット単位) を表す数値。サイズには、レスポンスヘッダーフィールドとレスポンスペイロードボディが含まれます。
performanceResourceTiming.encodedBodySize#
- 型: <number>
フェッチ (HTTP またはキャッシュ) から受信したペイロードボディのサイズ (オクテット単位) を表す数値。適用されたコンテンツエンコーディングを削除する前の値です。
performanceResourceTiming.decodedBodySize#
- 型: <number>
フェッチ (HTTP またはキャッシュ) から受信したメッセージボディのサイズ (オクテット単位) を表す数値。適用されたコンテンツエンコーディングを削除した後の値です。
performanceResourceTiming.toJSON()#
PerformanceResourceTiming オブジェクトの JSON 表現である object を返します。
クラス: PerformanceObserver#
new PerformanceObserver(callback)#
callback<Function>list<PerformanceObserverEntryList>observer<PerformanceObserver>
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[]>
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])#
name<string>type<string>- 戻り値: <PerformanceEntry[]>
performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.name が name と等しく、オプションで performanceEntry.entryType が type と等しいエントリが含まれます。
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)#
type<string>- 戻り値: <PerformanceEntry[]>
performanceEntry.startTime に関して時系列順に並んだ PerformanceEntry オブジェクトのリストを返します。このリストには、performanceEntry.entryType が type と等しいエントリが含まれます。
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>- 戻り値: <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.percentile(percentile)#
指定されたパーセンタイルの値を返します。
histogram.percentileBigInt(percentile)#
指定されたパーセンタイルの値を返します。
histogram.reset()#
収集されたヒストグラムデータをリセットします。
クラス: IntervalHistogram extends Histogram#
指定された間隔で定期的に更新される Histogram。
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.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');