- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v24.21.0 文档
- Node.js v24.21.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.eventLoopUtilization([utilization1[, utilization2]])perf_hooks.monitorEventLoopDelay([options])perf_hooks.timerify(fn[, options])- 类:
Histogramhistogram.counthistogram.countBigInthistogram.ccdf(value)histogram.cdf(value)histogram.cliffsD(other)histogram.cohensD(other)histogram.countAt(value)histogram.exceedshistogram.exceedsBigInthistogram.ewmaMeanhistogram.ewmaStddevhistogram.ewmaErrorRatehistogram.burnRate(sloTarget)histogram.ksTest(other)histogram.kurtosishistogram.linearBuckets(stepSize)histogram.logBuckets(firstBucket, base)histogram.mannWhitneyTest(other)histogram.maxhistogram.maxBigInthistogram.meanhistogram.minhistogram.minBigInthistogram.percentile(percentile)histogram.percentileBigInt(percentile)histogram.percentileCI(percentile[, options])histogram.percentileshistogram.percentilesBigInthistogram.percentilesAt(percentiles)histogram.reset()histogram.skewnesshistogram.stddevhistogram.welchTest(other[, options])
- 类:
ELDHistogram extends Histogram - 类:
RecordableHistogram 继承自 Histogram - 直方图分析示例
- 示例
- 性能测量 API
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
性能测量 API#>
🌐 Performance measurement APIs
源代码: lib/perf_hooks.js
该模块提供了 W3C 网页性能接口 子集的实现,以及用于 Node.js 特定性能测量的额外 API。
🌐 This module provides an implementation of a subset of the W3C Web Performance APIs as well as additional APIs for Node.js-specific performance measurements.
Node.js 支持以下 网页性能接口:
🌐 Node.js supports the following Web Performance APIs:
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。
🌐 An object that can be used to collect performance metrics from the current
Node.js instance. It is similar to window.performance in browsers.
performance.clearMarks([name])#>
name<string>
如果未提供 name,则从性能时间轴中删除所有 PerformanceMark 对象。如果提供了 name,则仅删除指定名称的标记。
🌐 If name is not provided, removes all PerformanceMark objects from the
Performance Timeline. If name is provided, removes only the named mark.
performance.clearMeasures([name])#>
name<string>
如果未提供 name,则从性能时间表中删除所有 PerformanceMeasure 对象。如果提供了 name,则仅删除指定名称的测量。
🌐 If name is not provided, removes all PerformanceMeasure objects from the
Performance Timeline. If name is provided, removes only the named measure.
performance.clearResourceTimings([name])#>
name<string>
如果未提供 name,则从资源时间轴中移除所有 PerformanceResourceTiming 对象。如果提供了 name,则仅移除指定名称的资源。
🌐 If name is not provided, removes all PerformanceResourceTiming objects from
the Resource Timeline. If name is provided, removes only the named resource.
performance.eventLoopUtilization([utilization1[, utilization2]])#>
utilization1<Object> 之前对eventLoopUtilization()调用的结果。utilization2<Object> 在调用utilization1之前对eventLoopUtilization()的先前调用结果。- 返回:<Object>
这是 perf_hooks.eventLoopUtilization() 的别名。
🌐 This is an alias of perf_hooks.eventLoopUtilization().
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
performance.getEntries()#>
返回按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。如果你只对某些类型或具有特定名称的性能条目感兴趣,请参阅 performance.getEntriesByType() 和 performance.getEntriesByName()。
🌐 Returns a list of PerformanceEntry objects in chronological order with
respect to performanceEntry.startTime. If you are only interested in
performance entries of certain types or that have certain names, see
performance.getEntriesByType() and performance.getEntriesByName().
performance.getEntriesByName(name[, type])#>
name<string>type<string>- 返回:<PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.name 等于 name,并且可选地,performanceEntry.entryType 等于 type。
🌐 Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.name is
equal to name, and optionally, whose performanceEntry.entryType is equal to
type.
performance.getEntriesByType(type)#>
type<string>- 返回:<PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,顺序基于 performanceEntry.startTime,且这些对象的 performanceEntry.entryType 等于 type。
🌐 Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.entryType
is equal to type.
performance.mark(name[, options])#>
在性能时间线中创建一个新的 PerformanceMark 条目。PerformanceMark 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'mark',且 performanceEntry.duration 始终为 0。性能标记用于标记性能时间线中的特定重要时刻。
🌐 Creates a new PerformanceMark entry in the Performance Timeline. A
PerformanceMark is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'mark', and whose
performanceEntry.duration is always 0. Performance marks are used
to mark specific significant moments in the Performance Timeline.
创建的 PerformanceMark 条目会被放入全局性能时间线中,并且可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当执行观察时,应使用 performance.clearMarks 手动将条目从全局性能时间线中清除。
🌐 The created PerformanceMark entry is put in the global Performance Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with performance.clearMarks.
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])#>
timingInfo<Object> 获取时间信息requestedUrl<string> 资源网址initiatorType<string> 发起者名称,例如:'fetch'global<Object>cacheMode<string> 缓存模式必须是空字符串('')或 'local'bodyInfo<Object> 获取响应主体信息responseStatus<number> 响应的状态码deliveryType<string> 交付类型。默认值:''。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
在资源时间线中创建一个新的 PerformanceResourceTiming 条目。PerformanceResourceTiming 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'resource'。性能资源用于标记资源时间线中的某些时刻。
🌐 Creates a new PerformanceResourceTiming entry in the Resource Timeline. A
PerformanceResourceTiming is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'resource'. Performance resources
are used to mark moments in the Resource Timeline.
创建的 PerformanceMark 条目会被放入全局资源时间线中,并且可以使用 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 查询。当执行观察时,应使用 performance.clearResourceTimings 手动从全局性能时间线中清除这些条目。
🌐 The created PerformanceMark entry is put in the global Resource Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with 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 经过的毫秒数。
🌐 Creates a new PerformanceMeasure entry in the Performance Timeline. A
PerformanceMeasure is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'measure', and whose
performanceEntry.duration measures the number of milliseconds elapsed since
startMark and endMark.
startMark 参数可以识别性能时间线中任何 已存在的 PerformanceMark,也可以识别 PerformanceNodeTiming 类提供的任何时间戳属性。如果指定的 startMark 不存在,则会抛出错误。
🌐 The startMark argument may identify any existing PerformanceMark in the
Performance Timeline, or may identify any of the timestamp properties
provided by the PerformanceNodeTiming class. If the named startMark does
not exist, an error is thrown.
可选的 endMark 参数必须标识性能时间线中任何 已存在 的 PerformanceMark,或 PerformanceNodeTiming 类提供的任何时间戳属性。如果未传递该参数,endMark 将为 performance.now();否则,如果指定的 endMark 不存在,将抛出错误。
🌐 The optional endMark argument must identify any existing PerformanceMark
in the Performance Timeline or any of the timestamp properties provided by the
PerformanceNodeTiming class. endMark will be performance.now()
if no parameter is passed, otherwise if the named endMark does not exist, an
error will be thrown.
创建的 PerformanceMeasure 条目会被放入全局性能时间线中,并且可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当执行观察时,应使用 performance.clearMeasures 手动清除全局性能时间线中的条目。
🌐 The created PerformanceMeasure entry is put in the global Performance Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with performance.clearMeasures.
performance.nodeTiming#>
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
PerformanceNodeTiming 类的一个实例,它提供特定 Node.js 操作里程碑的性能指标。
🌐 An instance of the PerformanceNodeTiming class that provides performance
metrics for specific Node.js operational milestones.
performance.now()#>
- 返回:<number>
返回当前高分辨率毫秒时间戳,其中 0 表示当前 node 进程的起始时间。
🌐 Returns the current high resolution millisecond timestamp, where 0 represents
the start of the current node process.
performance.setResourceTimingBufferSize(maxSize)#>
将全局性能资源计时缓冲区大小设置为指定数量的“resource”类型性能条目对象。
🌐 Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects.
默认情况下,最大缓冲区大小设置为 250。
🌐 By default the max buffer size is set to 250.
performance.timeOrigin#>
- 类型:<number>
timeOrigin 指定了当前 node 进程开始的高分辨率毫秒时间戳,以 Unix 时间为单位测量。
🌐 The timeOrigin specifies the high resolution millisecond timestamp at
which the current node process began, measured in Unix time.
performance.timerify(fn[, options])#>
fn<Function>options<Object>histogram<RecordableHistogram> 使用perf_hooks.createHistogram()创建的直方图对象,将记录以纳秒为单位的运行时持续时间。
这是 perf_hooks.timerify() 的别名。
🌐 This is an alias of perf_hooks.timerify().
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
performance.toJSON()#>
一个对象,它是 performance 对象的 JSON 表示形式。它类似于浏览器中的 window.performance.toJSON。
🌐 An object which is JSON representation of the performance object. It
is similar to window.performance.toJSON in browsers.
事件:'resourcetimingbufferfull'#>
🌐 Event: 'resourcetimingbufferfull'
当全局性能资源时序缓冲区已满时,会触发 'resourcetimingbufferfull' 事件。在事件监听器中,可以使用 performance.setResourceTimingBufferSize() 调整资源时序缓冲区大小,或者使用 performance.clearResourceTimings() 清空缓冲区,以便向性能时间线缓冲区添加更多条目。
🌐 The 'resourcetimingbufferfull' event is fired when the global performance
resource timing buffer is full. Adjust resource timing buffer size with
performance.setResourceTimingBufferSize() or clear the buffer with
performance.clearResourceTimings() in the event listener to allow
more entries to be added to the performance timeline buffer.
类:PerformanceEntry#>
🌐 Class: PerformanceEntry
此类的构造函数不直接暴露给用户。
🌐 The constructor of this class is not exposed to users directly.
performanceEntry.duration#>
- 类型:<number>
此条目的总经过毫秒数。该值并不适用于所有性能条目类型。
🌐 The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types.
performanceEntry.entryType#>
- 类型:<string>
性能条目的类型。它可以是以下之一:
🌐 The type of the performance entry. It may be one of:
'dns'(仅限 Node.js)'function'(仅限 Node.js)'gc'(仅限 Node.js)'http2'(仅限 Node.js)'http'(仅限 Node.js)'mark'(可在网上获得)'measure'(可在网上使用)'net'(仅限 Node.js)'node'(仅限 Node.js)'resource'(可在网上获得)
performanceEntry.name#>
- 类型:<string>
性能条目的名称。
🌐 The name of the performance entry.
performanceEntry.startTime#>
- 类型:<number>
标记性能条目开始时间的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp marking the starting time of the Performance Entry.
类:PerformanceMark#>
🌐 Class: PerformanceMark
显示通过 Performance.mark() 方法创建的标记。
🌐 Exposes marks created via the Performance.mark() method.
performanceMark.detail#>
- 类型:<any>
使用 Performance.mark() 方法创建时指定的附加详情。
🌐 Additional detail specified when creating with Performance.mark() method.
类:PerformanceMeasure#>
🌐 Class: PerformanceMeasure
公开通过 Performance.measure() 方法创建的指标。
🌐 Exposes measures created via the Performance.measure() method.
此类的构造函数不直接暴露给用户。
🌐 The constructor of this class is not exposed to users directly.
performanceMeasure.detail#>
- 类型:<any>
使用 Performance.measure() 方法创建时指定的附加详情。
🌐 Additional detail specified when creating with Performance.measure() method.
类:PerformanceNodeEntry#>
🌐 Class: PerformanceNodeEntry
该类是 Node.js 的一个扩展。在网页浏览器中不可用。
🌐 This class is an extension by Node.js. It is not available in Web browsers.
提供详细的 Node.js 时序数据。
🌐 Provides detailed Node.js timing data.
此类的构造函数不直接暴露给用户。
🌐 The constructor of this class is not exposed to users directly.
performanceNodeEntry.detail#>
- 类型:<any>
entryType 特有的附加细节。
🌐 Additional detail specific to the entryType.
performanceNodeEntry.flags#>
performanceNodeEntry.detail。- 类型:<number>
当 performanceEntry.entryType 等于 'gc' 时,performance.flags 属性包含有关垃圾回收操作的附加信息。其值可能为以下之一:
🌐 When performanceEntry.entryType is equal to 'gc', the performance.flags
property contains additional information about garbage collection operation.
The value may be one of:
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 属性会标识发生的垃圾回收操作类型。其值可能是以下之一:
🌐 When performanceEntry.entryType is equal to 'gc', the performance.kind
property identifies the type of garbage collection operation that occurred.
The value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_MINOR_MARK_SWEEPperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
垃圾回收('gc')详情#>
🌐 Garbage Collection ('gc') Details
当 performanceEntry.type 等于 'gc' 时,performanceNodeEntry.detail 属性将是一个具有两个属性的 <Object>:
🌐 When performanceEntry.type is equal to 'gc', the
performanceNodeEntry.detail property will be an <Object> with two properties:
kind<number> 其中之一:perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_MINOR_MARK_SWEEPperf_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')详情#>
🌐 HTTP ('http') Details
当 performanceEntry.type 等于 'http' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
🌐 When performanceEntry.type is equal to 'http', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.
如果 performanceEntry.name 等于 HttpClient,detail 将包含以下属性:req、res。其中 req 属性将是一个 <Object>,包含 method、url、headers,而 res 属性将是一个 <Object>,包含 statusCode、statusMessage、headers。
🌐 If performanceEntry.name is equal to HttpClient, the detail
will contain the following properties: req, res. And the req property
will be an <Object> containing method, url, headers, the res property
will be an <Object> containing statusCode, statusMessage, headers.
如果 performanceEntry.name 等于 HttpRequest,detail 将包含以下属性:req、res。其中 req 属性将是一个 <Object>,包含 method、url、headers,而 res 属性将是一个 <Object>,包含 statusCode、statusMessage、headers。
🌐 If performanceEntry.name is equal to HttpRequest, the detail
will contain the following properties: req, res. And the req property
will be an <Object> containing method, url, headers, the res property
will be an <Object> containing statusCode, statusMessage, headers.
这可能会增加额外的内存开销,应仅用于诊断目的,不应在生产环境中默认开启。
🌐 This could add additional memory overhead and should only be used for diagnostic purposes, not left turned on in production by default.
HTTP/2('http2')详情#>
🌐 HTTP/2 ('http2') Details
当 performanceEntry.type 等于 'http2' 时,performanceNodeEntry.detail 属性将是一个包含额外性能信息的 <Object>。
🌐 When performanceEntry.type is equal to 'http2', the
performanceNodeEntry.detail property will be an <Object> containing
additional performance information.
如果 performanceEntry.name 等于 Http2Stream,detail 将包含以下属性:
🌐 If performanceEntry.name is equal to Http2Stream, the detail
will contain the following properties:
bytesRead<number> 此Http2Stream接收到的DATA帧字节数。bytesWritten<number> 此Http2Stream发送的DATA帧字节数。id<number> 关联Http2Stream的标识符timeToFirstByte<number> 从PerformanceEntrystartTime到接收到第一个DATA帧之间经过的毫秒数。timeToFirstByteSent<number>PerformanceEntrystartTime与发送第一个DATA帧之间经过的毫秒数。timeToFirstHeader<number>PerformanceEntrystartTime与接收第一个头之间经过的毫秒数。
如果 performanceEntry.name 等于 Http2Session,detail 将包含以下属性:
🌐 If performanceEntry.name is equal to Http2Session, the detail will
contain the following properties:
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> 使用'server'或'client'来识别Http2Session的类型。
Timerify('函数')详情#>
🌐 Timerify ('function') Details
当 performanceEntry.type 等于 'function' 时,performanceNodeEntry.detail 属性将是一个 <Array>,列出被计时函数的输入参数。
🌐 When performanceEntry.type is equal to 'function', the
performanceNodeEntry.detail property will be an <Array> listing
the input arguments to the timed function.
净额('净额')详情#>
🌐 Net ('net') Details
当 performanceEntry.type 等于 'net' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
🌐 When performanceEntry.type is equal to 'net', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.
如果 performanceEntry.name 等于 connect,detail 将包含以下属性:host、port。
🌐 If performanceEntry.name is equal to connect, the detail
will contain the following properties: host, port.
DNS('dns')详细信息#>
🌐 DNS ('dns') Details
当 performanceEntry.type 等于 'dns' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
🌐 When performanceEntry.type is equal to 'dns', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.
如果 performanceEntry.name 等于 lookup,则 detail 将包含以下属性:hostname、family、hints、verbatim、addresses。
🌐 If performanceEntry.name is equal to lookup, the detail
will contain the following properties: hostname, family, hints, verbatim,
addresses.
如果 performanceEntry.name 等于 lookupService,则 detail 将包含以下属性:host、port、hostname、service。
🌐 If performanceEntry.name is equal to lookupService, the detail will
contain the following properties: host, port, hostname, service.
如果 performanceEntry.name 等于 queryxxx 或 getHostByAddr,则 detail 将包含以下属性:host、ttl、result。result 的值与 queryxxx 或 getHostByAddr 的结果相同。
🌐 If performanceEntry.name is equal to queryxxx or getHostByAddr, the detail will
contain the following properties: host, ttl, result. The value of result is
same as the result of queryxxx or getHostByAddr.
类:PerformanceNodeTiming#>
🌐 Class: PerformanceNodeTiming
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
提供 Node.js 本身的时间详情。该类的构造函数不向用户公开。
🌐 Provides timing details for Node.js itself. The constructor of this class is not exposed to users.
performanceNodeTiming.bootstrapComplete#>
- 类型:<number>
Node.js 进程完成引导的高分辨率毫秒时间戳。如果引导尚未完成,该属性的值为 -1。
🌐 The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1.
performanceNodeTiming.environment#>
- 类型:<number>
Node.js 环境初始化时的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp at which the Node.js environment was initialized.
performanceNodeTiming.idleTime#>
- 类型:<number>
事件循环在其事件提供者(例如 epoll_wait)中空闲的高分辨率毫秒时间戳。这不考虑 CPU 使用情况。如果事件循环尚未启动(例如,在主脚本的第一个时钟周期中),该属性的值为 0。
🌐 The high resolution millisecond timestamp of the amount of time the event loop
has been idle within the event loop's event provider (e.g. epoll_wait). This
does not take CPU usage into consideration. If the event loop has not yet
started (e.g., in the first tick of the main script), the property has the
value of 0.
performanceNodeTiming.loopExit#>
- 类型:<number>
Node.js 事件循环退出的高分辨率毫秒时间戳。如果事件循环尚未退出,该属性的值为 -1。只有在 'exit' 事件的处理程序中,该值才可能不是 -1。
🌐 The high resolution millisecond timestamp at which the Node.js event loop
exited. If the event loop has not yet exited, the property has the value of -1.
It can only have a value of not -1 in a handler of the 'exit' event.
performanceNodeTiming.loopStart#>
- 类型:<number>
Node.js 事件循环开始的高精度毫秒时间戳。如果事件循环尚未开始(例如,在主脚本的第一次迭代中),该属性的值为 -1。
🌐 The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1.
performanceNodeTiming.nodeStart#>
- 类型:<number>
Node.js 进程初始化时的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp at which the Node.js process was initialized.
performanceNodeTiming.uvMetricsInfo#>
- 返回:<Object>
这是 uv_metrics_info 函数的封装。它返回当前的一组事件循环指标。
🌐 This is a wrapper to the uv_metrics_info function.
It returns the current set of event loop metrics.
建议在使用 setImmediate 安排执行的函数中使用此属性,以避免在完成当前循环迭代期间安排的所有操作之前收集指标。
🌐 It is recommended to use this property inside a function whose execution was
scheduled using setImmediate to avoid collecting metrics before finishing all
operations scheduled during the current loop iteration.
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#>
- 类型:<number>
V8 平台初始化时的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp at which the V8 platform was initialized.
类:PerformanceResourceTiming#>
🌐 Class: PerformanceResourceTiming
提供有关应用资源加载的详细网络时间数据。
🌐 Provides detailed network timing data regarding the loading of an application's resources.
此类的构造函数不直接暴露给用户。
🌐 The constructor of this class is not exposed to users directly.
performanceResourceTiming.workerStart#>
- 类型:<number>
在调度 fetch 请求之前的高分辨率毫秒时间戳。如果资源未被 worker 拦截,则该属性始终返回 0。
🌐 The high resolution millisecond timestamp at immediately before dispatching
the fetch request. If the resource is not intercepted by a worker the property
will always return 0.
performanceResourceTiming.redirectStart#>
- 类型:<number>
表示启动重定向的抓取开始时间的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp that represents the start time of the fetch which initiates the redirect.
performanceResourceTiming.redirectEnd#>
- 类型:<number>
在接收到最后一次重定向的响应的最后一个字节后立即创建的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp that will be created immediately after receiving the last byte of the response of the last redirect.
performanceResourceTiming.fetchStart#>
- 类型:<number>
在 Node.js 开始获取资源之前的高分辨率毫秒时间戳。
🌐 The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource.
performanceResourceTiming.domainLookupStart#>
- 类型:<number>
在 Node.js 开始为资源进行域名查找之前的高精度毫秒时间戳。
🌐 The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup for the resource.
performanceResourceTiming.domainLookupEnd#>
- 类型:<number>
高分辨率毫秒时间戳,表示 Node.js 完成资源的域名查询后立即的时间。
🌐 The high resolution millisecond timestamp representing the time immediately after the Node.js finished the domain name lookup for the resource.
performanceResourceTiming.connectStart#>
- 类型:<number>
高分辨率毫秒时间戳,表示 Node.js 在开始建立与服务器的连接以获取资源之前的时间。
🌐 The high resolution millisecond timestamp representing the time immediately before Node.js starts to establish the connection to the server to retrieve the resource.
performanceResourceTiming.connectEnd#>
- 类型:<number>
高精度毫秒时间戳,表示 Node.js 完成与服务器建立连接以获取资源后立即的时间。
🌐 The high resolution millisecond timestamp representing the time immediately after Node.js finishes establishing the connection to the server to retrieve the resource.
performanceResourceTiming.secureConnectionStart#>
- 类型:<number>
高分辨率毫秒时间戳,表示 Node.js 在开始握手以保护当前连接之前的时间。
🌐 The high resolution millisecond timestamp representing the time immediately before Node.js starts the handshake process to secure the current connection.
performanceResourceTiming.requestStart#>
- 类型:<number>
高精度毫秒时间戳,表示 Node.js 在接收到服务器响应的第一个字节之前的时间。
🌐 The high resolution millisecond timestamp representing the time immediately before Node.js receives the first byte of the response from the server.
performanceResourceTiming.responseEnd#>
- 类型:<number>
高精度毫秒时间戳,表示在 Node.js 接收到资源的最后一个字节后或在传输连接关闭前(以先发生者为准)的时间。
🌐 The high resolution millisecond timestamp representing the time immediately after Node.js receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
performanceResourceTiming.transferSize#>
- 类型:<number>
表示获取的资源大小(以字节为单位)的数字。大小包括响应头字段以及响应负载主体。
🌐 A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body.
performanceResourceTiming.encodedBodySize#>
- 类型:<number>
表示从 fetch(HTTP 或缓存)接收的有效负载主体大小(以字节为单位)的数字,单位是在去除任何应用的内容编码之前。
🌐 A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings.
performanceResourceTiming.decodedBodySize#>
- 类型:<number>
表示从 fetch(HTTP 或缓存)接收的消息主体的大小(以字节为单位)的数字,已去除任何应用的内容编码。
🌐 A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after removing any applied content-codings.
performanceResourceTiming.toJSON()#>
返回一个 object,它是 PerformanceResourceTiming 对象的 JSON 表示
🌐 Returns a object that is the JSON representation of the
PerformanceResourceTiming object
类:PerformanceObserver#>
🌐 Class: PerformanceObserver
PerformanceObserver.supportedEntryTypes#>
- 类型:<string[]>
获取支持的类型。
🌐 Get supported types.
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 实例会引入额外的性能开销,因此不应无限期地保持订阅通知。当不再需要时,用户应尽快断开观察者。
🌐 Because PerformanceObserver instances introduce their own additional
performance overhead, instances should not be left subscribed to notifications
indefinitely. Users should disconnect observers as soon as they are no
longer needed.
callback 会在 PerformanceObserver 被通知有新的 PerformanceEntry 实例时被调用。该回调接收一个 PerformanceObserverEntryList 实例以及对 PerformanceObserver 的引用。
🌐 The callback is invoked when a PerformanceObserver is
notified about new PerformanceEntry instances. The callback receives a
PerformanceObserverEntryList instance and a reference to the
PerformanceObserver.
performanceObserver.disconnect()#>
将 PerformanceObserver 实例与所有通知断开连接。
🌐 Disconnects the PerformanceObserver instance from all notifications.
performanceObserver.observe(options)#>
options<Object>type<string> 单一 <PerformanceEntry> 类型。如果已经指定了entryTypes,则不得提供。entryTypes<string[]> 一个字符串数组,用于标识观察者感兴趣的 <PerformanceEntry> 实例类型。如果未提供,则会抛出错误。buffered<boolean> 如果为真,观察者回调将使用全局PerformanceEntry缓冲条目的列表调用。如果为假,则只有在该时间点之后创建的PerformanceEntry会发送到观察者回调。默认值:false。
将 <PerformanceObserver> 实例订阅到新 <PerformanceEntry> 实例的通知,这些实例可以通过 options.entryTypes 或 options.type 标识:
🌐 Subscribes the <PerformanceObserver> instance to notifications of new
<PerformanceEntry> instances identified either by options.entryTypes
or options.type:
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#>
🌐 Class: PerformanceObserverEntryList
PerformanceObserverEntryList 类用于提供对传递给 PerformanceObserver 的 PerformanceEntry 实例的访问。该类的构造函数不对用户开放。
🌐 The PerformanceObserverEntryList class is used to provide access to the
PerformanceEntry instances passed to a PerformanceObserver.
The constructor of this class is not exposed to users.
performanceObserverEntryList.getEntries()#>
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。
🌐 Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime.
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 对象列表,其 performanceEntry.name 等于 name,并且可选地,performanceEntry.entryType 等于 type。
🌐 Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.name is
equal to name, and optionally, whose performanceEntry.entryType is equal to
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 对象列表,顺序基于 performanceEntry.startTime,且这些对象的 performanceEntry.entryType 等于 type。
🌐 Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.entryType
is equal to 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>lowest<number> | <bigint> 可检测到的最低值。必须是大于 0 的整数值。默认值:1。highest<number> | <bigint> 可记录的最高值。必须是一个整数,并且大于或等于lowest的两倍。默认值:Number.MAX_SAFE_INTEGER。figures<number> 精度位数。必须是介于1和5之间的数字。默认值:3。halfLife<number> EWMA 的半衰期,以样本数表示。当设置为大于 0 的值时,直方图会跟踪一个指数加权移动平均值和标准差,可通过histogram.ewmaMean和histogram.ewmaStddev访问。在halfLife次记录后,一个值的影响力会衰减到 50%。默认:0(禁用)。threshold<number> SLO 阈值。当与halfLife一起设置时,直方图会跟踪超过该阈值的平滑错误率,可通过histogram.ewmaErrorRate和histogram.burnRate()访问。默认值:0(禁用)。
- 返回:<RecordableHistogram>
返回一个 <RecordableHistogram>。
🌐 Returns a <RecordableHistogram>.
perf_hooks.eventLoopUtilization([utilization1[, utilization2]])#>
utilization1<Object> 之前对eventLoopUtilization()调用的结果。utilization2<Object> 在调用utilization1之前对eventLoopUtilization()的先前调用结果。- 返回:<Object>
eventLoopUtilization() 函数返回一个对象,该对象包含事件循环在空闲和活动状态下的累计持续时间,单位为高精度毫秒计时器。utilization 值是计算得出的事件循环利用率(ELU)。
🌐 The eventLoopUtilization() function returns an object that contains the
cumulative duration of time the event loop has been both idle and active as a
high resolution milliseconds timer. The utilization value is the calculated
Event Loop Utilization (ELU).
如果主线程上的自举尚未完成,这些属性的值为 0。由于自举在事件循环中进行,ELU 在 工作线程 上可以立即使用。
🌐 If bootstrapping has not yet finished on the main thread the properties have
the value of 0. The ELU is immediately available on Worker threads since
bootstrap happens within the event loop.
utilization1 和 utilization2 都是可选参数。
🌐 Both utilization1 and utilization2 are optional parameters.
如果传入 utilization1,则会计算并返回当前调用的 active 和 idle 时间之间的差值,以及相应的 utilization 值(类似于 process.hrtime())。
🌐 If utilization1 is passed, then the delta between the current call's active
and idle times, as well as the corresponding utilization value are
calculated and returned (similar to process.hrtime()).
如果同时传入 utilization1 和 utilization2,则会计算这两个参数之间的差值。这是一个方便的选项,因为与 process.hrtime() 不同,计算 ELU 比单一减法更复杂。
🌐 If utilization1 and utilization2 are both passed, then the delta is
calculated between the two arguments. This is a convenience option because,
unlike process.hrtime(), calculating the ELU is more complex than a
single subtraction.
ELU 类似于 CPU 利用率,不同之处在于它只衡量事件循环的统计数据,而不包括 CPU 使用情况。它表示事件循环在事件提供者(例如 epoll_wait)之外所花费时间的百分比。其他的 CPU 空闲时间不予考虑。下面是一个示例,说明一个大部分时间处于空闲状态的进程将具有较高的 ELU。
🌐 ELU is similar to CPU utilization, except that it only measures event loop
statistics and not CPU usage. It represents the percentage of time the event
loop has spent outside the event loop's event provider (e.g. epoll_wait).
No other CPU idle time is taken into consideration. The following is an example
of how a mostly idle process will have a high 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);
});const { eventLoopUtilization } = require('node:perf_hooks');
const { spawnSync } = require('node:child_process');
setImmediate(() => {
const elu = eventLoopUtilization();
spawnSync('sleep', ['5']);
console.log(eventLoopUtilization(elu).utilization);
});
虽然在运行此脚本时 CPU 大部分处于空闲状态,但 utilization 的值是 1。这是因为对 child_process.spawnSync() 的调用阻塞了事件循环的进行。
🌐 Although the CPU is mostly idle while running this script, the value of
utilization is 1. This is because the call to
child_process.spawnSync() blocks the event loop from proceeding.
传入用户定义的对象而不是之前对 eventLoopUtilization() 调用的结果将导致未定义行为。返回值不能保证反映事件循环的任何正确状态。
🌐 Passing in a user-defined object instead of the result of a previous call to
eventLoopUtilization() will lead to undefined behavior. The return values
are not guaranteed to reflect any correct state of the event loop.
perf_hooks.monitorEventLoopDelay([options])#>
options<Object>- 返回:ELDHistogram
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
创建一个直方图对象,用来采样并报告事件循环随时间的延迟。这些延迟将以纳秒为单位报告。
🌐 Creates a histogram object that samples and reports the event loop delay over time. The delays will be reported in nanoseconds.
默认情况下,直方图会通过使用配置好的resolution的定时器来更新。当samplePerIteration为true时,会使用uv_prepare_t和uv_check_t钩子在每次事件循环迭代中采样。在这种模式下,直方图不会保持循环运行,也不会在应用空闲时强制进行额外的迭代。这两种采样模式产生的结果差异很大,不应直接比较。
🌐 By default, the histogram is updated by a timer using the configured
resolution. When samplePerIteration is true, samples are taken once per
event loop iteration using uv_prepare_t and uv_check_t hooks. In that mode,
the histogram does not keep the loop alive or force additional iterations when
the application is idle.
The two sampling modes produce significantly different results and should not
be compared directly.
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));
perf_hooks.timerify(fn[, options])#>
fn<Function>options<Object>histogram<RecordableHistogram> 使用perf_hooks.createHistogram()创建的直方图对象,将记录以纳秒为单位的运行时持续时间。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
🌐 This property is an extension by Node.js. It is not available in Web browsers.
将一个函数封装在一个新函数中,该新函数会测量被封装函数的运行时间。必须订阅 'function' 事件类型的 PerformanceObserver,才能访问计时详情。
🌐 Wraps a function within a new function that measures the running time of the
wrapped function. A PerformanceObserver must be subscribed to the 'function'
event type in order for the timing details to be accessed.
import { timerify, performance, PerformanceObserver } from 'node:perf_hooks';
function someFunction() {
console.log('hello world');
}
const wrapped = 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 {
timerify,
performance,
PerformanceObserver,
} = require('node:perf_hooks');
function someFunction() {
console.log('hello world');
}
const wrapped = 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,将会在该 Promise 上附加一个 finally 处理程序,并且一旦 finally 处理程序被调用,持续时间就会被报告。
🌐 If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported once the finally handler is invoked.
类:Histogram#>
🌐 Class: Histogram
histogram.count#>
- 类型:<number>
直方图记录的样本数。
🌐 The number of samples recorded by the histogram.
histogram.countBigInt#>
- 类型:<bigint>
直方图记录的样本数。
🌐 The number of samples recorded by the histogram.
histogram.ccdf(value)#>
返回给定值的互补累积分布函数(CCDF)值,表示记录值超过 value 的概率。等同于 1 - histogram.cdf(value)。
🌐 Returns the complementary cumulative distribution function (CCDF) value
for the given value, representing the probability that a recorded value
will exceed value. Equivalent to 1 - histogram.cdf(value).
histogram.cdf(value)#>
返回给定值的累积分布函数(CDF)值,表示记录值小于或等于 value 的概率。这是 histogram.percentile() 的逆运算。
🌐 Returns the cumulative distribution function (CDF) value for the given
value, representing the probability that a recorded value will be less
than or equal to value. This is the inverse operation of
histogram.percentile().
histogram.cliffsD(other)#>
other<Histogram> 用来比较的直方图。- 返回:<number> 一个介于 -1.0 和 1.0 之间的值。
计算 克利夫的德尔塔,一种非参数效应量度。返回的是这个直方图中随机值超过 other 中随机值的概率减去相反概率。值为 1 表示这个直方图中的每个值都超过 other 中的每个值;-1 表示相反;0 表示没有任何倾向。
🌐 Computes Cliff's delta, a non-parametric effect size measure. Returns
the probability that a random value from this histogram exceeds a random
value from other, minus the reverse probability. A value of 1 means every
value in this histogram exceeds every value in other; -1 means the
opposite; 0 means no tendency in either direction.
histogram.cohensD(other)#>
other<Histogram> 用来比较的直方图。- 返回:<number> 效应大小
计算 科恩的d 的效应量,即这个直方图与 other 平均值之间的标准化差异,使用合并标准差。正值表示这个直方图的平均值更高。按照惯例,|d| < 0.2 属于小效应,0.5 属中等效应,0.8 或以上属于大效应。两个直方图都必须至少有 2 个记录值,否则返回 0。
🌐 Computes Cohen's d effect size, the standardized difference between the
means of this histogram and other, using the pooled standard deviation.
Positive values indicate this histogram has a higher mean. By convention,
|d| < 0.2 is a small effect, 0.5 is medium, and 0.8 or greater is large.
Both histograms must have at least 2 recorded values; otherwise returns 0.
histogram.countAt(value)#>
返回落在给定值的等效值范围内的已记录值的数量。
🌐 Returns the number of recorded values that fall within the equivalent value range of the given value.
histogram.exceeds#>
- 类型:<number>
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
🌐 The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
histogram.exceedsBigInt#>
- 类型:<bigint>
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
🌐 The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
histogram.ewmaMean#>
- 类型:<number>
记录值的指数加权移动平均。只有当直方图使用大于 0 的 halfLife 选项创建时才会生效。当 EWMA 被禁用或没有记录任何值时,返回 0。
🌐 The exponentially weighted moving average of recorded values. Only active
when the histogram was created with a halfLife option greater than 0.
Returns 0 when EWMA is disabled or no values have been recorded.
histogram.ewmaStddev#>
- 类型:<number>
指数加权移动标准差。只有在使用大于 0 的 halfLife 选项创建直方图时才会生效。当 EWMA 被禁用或没有记录任何值时,返回 0。
🌐 The exponentially weighted moving standard deviation. Only active when the
histogram was created with a halfLife option greater than 0. Returns 0
when EWMA is disabled or no values have been recorded.
histogram.ewmaErrorRate#>
- 类型:<number>
记录值超过配置的 threshold 的 EWMA 平滑概率。仅在使用 halfLife 和 threshold 选项创建直方图时才会启用。如果未启用或未记录任何值,则返回 0。
🌐 The EWMA-smoothed probability of a recorded value exceeding the configured
threshold. Only active when the histogram was created with both halfLife
and threshold options. Returns 0 when not enabled or no values have been
recorded.
histogram.burnRate(sloTarget)#>
返回 SLO 消耗速率:ewmaErrorRate / (1 - sloTarget)。消耗速率为 1 表示在 SLO 窗口期内错误预算将被完全耗尽。消耗速率大于 1 表示消耗速度超过允许值。要求直方图必须使用 halfLife 和 threshold 选项创建。
🌐 Returns the SLO burn rate: ewmaErrorRate / (1 - sloTarget). A burn rate
of 1 means the error budget will be exactly exhausted over the SLO window.
A burn rate greater than 1 means it is being consumed faster than allowed.
Requires the histogram to have been created with both halfLife and
threshold options.
const { createHistogram } = require('node:perf_hooks');
// Track latency with a 200ms SLO threshold, half-life of 100 samples
const h = createHistogram({ halfLife: 100, threshold: 200_000_000 });
// ... record latency values ...
// Check burn rate against a 99.9% SLO
const rate = h.burnRate(0.999);
if (rate > 1) {
console.log(`SLO burn rate: ${rate.toFixed(2)}x — error budget depleting`);
}
histogram.ksTest(other)#>
other<Histogram> 用来比较的直方图。- 返回:<number> KS D统计量,介于0.0和1.0之间。
计算 Kolmogorov-Smirnov 检验统计量,用于比较此直方图的分布与 other 的分布。值为 0 表示分布相同;接近 1 的值表示分布完全不相交。通过比较前后的直方图,用于检测性能回归很有用。
🌐 Computes the Kolmogorov-Smirnov test statistic comparing this histogram's
distribution to other. A value of 0 indicates identical distributions;
values close to 1 indicate completely disjoint distributions. Useful for
detecting performance regressions by comparing before/after histograms.
histogram.kurtosis#>
- 类型:<number>
记录值的超峰度。衡量分布尾部相对于正态分布的厚度。正值表示尾部更厚(极端离群值更多);负值表示尾部更轻。
🌐 The excess kurtosis of the recorded values. Measures the heaviness of the distribution's tails relative to a normal distribution. Positive values indicate heavier tails (more extreme outliers); negative values indicate lighter tails.
histogram.linearBuckets(stepSize)#>
返回重新分桶到线性间隔为 stepSize 的直方图数据。适合可视化和导出。
🌐 Returns the histogram data rebucketed into linearly-spaced intervals
of stepSize. Useful for visualization and export.
histogram.logBuckets(firstBucket, base)#>
返回按对数间隔重新分桶的直方图数据,每个桶的宽度乘以 base。适合用于可视化和导出。
🌐 Returns the histogram data rebucketed into logarithmically-spaced
intervals, where each bucket's width is multiplied by base.
Useful for visualization and export.
histogram.mannWhitneyTest(other)#>
other<Histogram> 用来比较的直方图。- 返回:<Object>
执行 曼-惠特尼 U 检验 来比较这个直方图是否倾向于产生比 other 更大或更小的值。与 welchTest() 不同,这是一个非参数检验,不对分布的形状做任何假设。使用带有并列修复的正态近似来计算 p 值。
🌐 Performs a Mann-Whitney U test comparing whether this histogram tends to
produce larger or smaller values than other. Unlike welchTest(), this is a
non-parametric test that makes no assumptions about the shape of the
distributions. Uses the normal approximation with tie correction for the
p-value.
histogram.max#>
- 类型:<number>
记录的事件循环延迟的最大值。
🌐 The maximum recorded event loop delay.
histogram.maxBigInt#>
- 类型:<bigint>
记录的事件循环延迟的最大值。
🌐 The maximum recorded event loop delay.
histogram.mean#>
- 类型:<number>
记录的事件循环延迟的平均值。
🌐 The mean of the recorded event loop delays.
histogram.min#>
- 类型:<number>
记录的事件循环延迟的最小值。
🌐 The minimum recorded event loop delay.
histogram.minBigInt#>
- 类型:<bigint>
记录的事件循环延迟的最小值。
🌐 The minimum recorded event loop delay.
histogram.percentile(percentile)#>
返回给定的百分位数的值。
🌐 Returns the value at the given percentile.
histogram.percentileBigInt(percentile)#>
返回给定的百分位数的值。
🌐 Returns the value at the given percentile.
histogram.percentileCI(percentile[, options])#>
percentile<number> 百分位值,范围在 (0, 100]。options<Object>confidence<number> 区间的置信水平,在 0 和 1 之间(不包括0和1)。默认值:0.95。
- 返回:<Object>
使用精确二项式方法返回给定百分位数的置信区间。样本越少,区间越宽,反映出百分位数估计的不确定性越大。至少需要记录 2 个值;如果少于 2 个,lower 和 upper 将等于 value。
🌐 Returns a confidence interval for the given percentile using the exact
binomial method. With fewer samples, the interval will be wider, reflecting
the greater uncertainty in the percentile estimate. Requires at least 2
recorded values; with fewer than 2, lower and upper will equal value.
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
for (let i = 0; i < 1000; i++) {
h.record(Math.floor(Math.random() * 100));
}
const ci = h.percentileCI(99);
console.log(ci.value); // The p99 point estimate
console.log(ci.lower); // The lower bound (95% confidence)
console.log(ci.upper); // The upper bound (95% confidence)
histogram.percentiles#>
- 类型:<Map>
返回一个 Map 对象,详细说明累计百分比分布。
🌐 Returns a Map object detailing the accumulated percentile distribution.
histogram.percentilesBigInt#>
- 类型:<Map>
返回一个 Map 对象,详细说明累计百分比分布。
🌐 Returns a Map object detailing the accumulated percentile distribution.
histogram.percentilesAt(percentiles)#>
percentiles<number[]> 一个位于 (0, 100] 范围内的百分位值数组。- 返回:<Map> 百分位值对应直方图值的地图。
返回指定百分位的值,通过对直方图数据进行一次高效遍历计算出来的。比多次调用 histogram.percentile() 更高效。
🌐 Returns the values at the specified percentiles, computed in a single
efficient pass over the histogram data. More efficient than calling
histogram.percentile() multiple times.
histogram.reset()#>
重置收集的直方图数据。
🌐 Resets the collected histogram data.
histogram.skewness#>
- 类型:<number>
记录值的偏度。衡量分布的非对称性。正值表示右偏分布(右尾较长,延迟数据常见);负值表示左偏分布。
🌐 The skewness of the recorded values. Measures the asymmetry of the distribution. A positive value indicates a right-skewed distribution (longer right tail, common for latency data); a negative value indicates a left-skewed distribution.
histogram.stddev#>
- 类型:<number>
记录的事件循环延迟的标准偏差。
🌐 The standard deviation of the recorded event loop delays.
histogram.welchTest(other[, options])#>
other<Histogram> 用来比较的直方图。options<Object>confidence<number> 区间的置信水平,介于 0 和 1 之间。 默认值:0.95。
- 返回:<Object>
执行 Welch t检验,对这个直方图和 other 的均值进行比较。p 值表示在零假设(即两个分布均值相同)下,观察到至少这么极端差异的概率。两个直方图都必须至少有 2 个记录值,否则结果会是 pValue 1 和 tStatistic 0。
🌐 Performs Welch's t-test comparing the means of this histogram and other.
The p-value indicates the probability of observing a difference at least this
extreme under the null hypothesis that the two distributions have the same
mean. Both histograms must have at least 2 recorded values; otherwise the
result has pValue 1 and tStatistic 0.
类:ELDHistogram extends Histogram#>
🌐 Class: ELDHistogram extends Histogram
一个记录事件循环延迟的 Histogram,由 perf_hooks.monitorEventLoopDelay() 返回。
🌐 A Histogram that records event loop delay, returned by
perf_hooks.monitorEventLoopDelay().
histogram.disable()#>
- 返回:<boolean>
禁用事件循环延迟采样。如果采样被停止,返回 true;如果采样已经停止,返回 false。
🌐 Disables event loop delay sampling. Returns true if sampling was
stopped, false if it was already stopped.
histogram.enable()#>
- 返回:<boolean>
启用事件循环延迟采样。如果采样已启动,则返回 true;如果已经启动过,则返回 false。
🌐 Enables event loop delay sampling. Returns true if sampling was
started, false if it was already started.
histogram[Symbol.dispose]()#>
当直方图被释放时,禁用事件循环延迟采样。
🌐 Disables event loop delay sampling when the histogram is disposed.
const { monitorEventLoopDelay } = require('node:perf_hooks');
{
using hist = monitorEventLoopDelay({ resolution: 20 });
hist.enable();
// The histogram will be disabled when the block is exited.
}
克隆一个 ELDHistogram#>
🌐 Cloning an ELDHistogram
ELDHistogram 实例可以通过 <MessagePort> 克隆。在接收端,直方图会被克隆为一个普通的 <Histogram> 对象,该对象不实现 enable() 和 disable() 方法。
类:RecordableHistogram 继承自 Histogram#>
🌐 Class: RecordableHistogram extends Histogram
histogram.add(other)#>
other<RecordableHistogram>
将 other 中的值添加到此直方图中。
🌐 Adds the values from other to this histogram.
histogram.record(val)#>
histogram.recordDelta()#>
计算自上一次调用 recordDelta() 以来经过的时间(以纳秒为单位),并将该时间记录到直方图中。
🌐 Calculates the amount of time (in nanoseconds) that has passed since the
previous call to recordDelta() and records that amount in the histogram.
histogram.recordCorrected(val, expectedInterval)#>
记录一个带有协调遗漏修复的值。当系统停顿导致无法及时记录时,这个方法会在之前记录的值和 val 之间以 expectedInterval 步长回填中间值。这样可以补偿测量空白,否则这些空白会低估延迟。
🌐 Records a value with coordinated omission correction. When a system stall
prevents timely recording, this method backfills intermediate values at
expectedInterval steps between the previously recorded value and val.
This compensates for measurement gaps that would otherwise underrepresent
latency.
histogram.subtract(other)#>
other<RecordableHistogram>
从这个直方图中减去 other 的值。两个直方图应该有兼容的配置。变为负数的桶计数会被限制为零。
🌐 Subtracts the values of other from this histogram. Both histograms should
have compatible configurations. Bucket counts that would become negative
are clamped to zero.
直方图分析示例#>
🌐 Histogram analysis examples
Histogram 类提供了用于性能监控、SLO 执行和回归检测的统计分析方法。
🌐 The Histogram class provides statistical analysis methods useful for
performance monitoring, SLO enforcement, and regression detection.
分布形状分析#>
🌐 Distribution shape analysis
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
// Simulate a right-skewed latency distribution
for (let i = 0; i < 1000; i++) {
h.record(Math.ceil(Math.random() * 100));
}
// Add some outliers
for (let i = 0; i < 10; i++) {
h.record(500 + Math.ceil(Math.random() * 500));
}
console.log('Skewness:', h.skewness.toFixed(4)); // Positive = right-skewed
console.log('Kurtosis:', h.kurtosis.toFixed(4)); // Positive = heavy tails
使用CDF进行SLO监控#>
🌐 SLO monitoring with CDF
const { createHistogram } = require('node:perf_hooks');
const latency = createHistogram();
// Record request latencies (in nanoseconds)...
// "What fraction of requests complete within 100ms?"
const withinSLO = latency.cdf(100_000_000);
console.log(`${(withinSLO * 100).toFixed(1)}% of requests within SLO`);
// "What fraction of requests exceed 500ms?"
const violating = latency.ccdf(500_000_000);
console.log(`${(violating * 100).toFixed(1)}% of requests violating SLO`);
SLO 消耗率监控#>
🌐 SLO burn rate monitoring
const { createHistogram } = require('node:perf_hooks');
// Track latency with EWMA (half-life 100 samples) and a 200ms SLO threshold
const latency = createHistogram({
halfLife: 100,
threshold: 200_000_000, // 200ms in nanoseconds
});
// Record request latencies...
// Smoothed error rate: probability of exceeding the threshold
console.log(`Error rate: ${(latency.ewmaErrorRate * 100).toFixed(2)}%`);
// Burn rate against a 99.9% SLO
// >1 means the error budget is depleting faster than allowed
const rate = latency.burnRate(0.999);
console.log(`Burn rate: ${rate.toFixed(2)}x`);
// EWMA mean and stddev track the smoothed latency
console.log(`EWMA latency: ${latency.ewmaMean.toFixed(0)}ns`);
console.log(`EWMA stddev: ${latency.ewmaStddev.toFixed(0)}ns`);
使用KS检验进行回归检测#>
🌐 Regression detection with KS test
const { createHistogram } = require('node:perf_hooks');
const baseline = createHistogram();
const current = createHistogram();
// Record baseline and current latencies...
// D-statistic: 0 = identical, 1 = completely different
const d = baseline.ksTest(current);
if (d > 0.1) {
console.log(`Possible regression detected (D=${d.toFixed(4)})`);
}
批量百分位查询#>
🌐 Batch percentile queries
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
// Record values...
// Efficiently query common monitoring percentiles in one pass
const p = h.percentilesAt([50, 75, 90, 95, 99, 99.9]);
console.log('p50:', p.get(50));
console.log('p99:', p.get(99));
使用减法进行快照比较#>
🌐 Snapshot diffing with subtract
const { createHistogram } = require('node:perf_hooks');
const total = createHistogram();
const snapshot = createHistogram();
// Record values into total...
// Periodically snapshot for "last interval" analysis:
snapshot.add(total);
// Later, take a new snapshot and diff:
const newSnapshot = createHistogram();
newSnapshot.add(total);
newSnapshot.subtract(snapshot);
// newSnapshot now contains only the values recorded since the last snapshot
console.log('Recent p99:', newSnapshot.percentile(99));
与韦尔奇t检验的基准比较#>
🌐 Benchmark comparison with Welch's t-test
const { createHistogram } = require('node:perf_hooks');
const baseline = createHistogram();
const candidate = createHistogram();
// Record operation rates from the old and new builds...
const result = baseline.welchTest(candidate);
const improvement = ((candidate.mean - baseline.mean) / baseline.mean * 100);
console.log(`Improvement: ${improvement.toFixed(2)}%`);
console.log(`p-value: ${result.pValue.toFixed(6)}`);
console.log(`95% CI: [${result.confidenceInterval.lower.toFixed(2)}, ` +
`${result.confidenceInterval.upper.toFixed(2)}]`);
if (result.pValue < 0.05) {
const d = baseline.cohensD(candidate);
console.log(`Statistically significant (Cohen's d = ${d.toFixed(4)})`);
}
使用Cliff的delta计算效应量#>
🌐 Effect size with Cliff's delta
const { createHistogram } = require('node:perf_hooks');
const before = createHistogram();
const after = createHistogram();
// Record latencies before and after a change...
const delta = before.cliffsD(after);
// A delta > 0: before tends to produce larger values (improvement)
// A delta < 0: after tends to produce larger values (regression)
console.log(`Cliff's delta: ${delta.toFixed(4)}`);
示例#>
🌐 Examples
测量异步操作的持续时间#>
🌐 Measuring the duration of async operations
以下示例使用 异步钩子 和 Performance API 来测量 Timeout 操作的实际持续时间(包括执行回调所花费的时间)。
🌐 The following example uses the Async Hooks and Performance APIs to measure the actual duration of a Timeout operation (including the amount of time it took to execute the callback).
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);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);
测量加载依赖需要多长时间#>
🌐 Measuring how long it takes to load dependencies
以下示例测量 require() 操作加载依赖的持续时间:
🌐 The following example measures the duration of require() operations to load
dependencies:
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');
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 往返需要多长时间#>
🌐 Measuring how long one HTTP round-trip takes
以下示例用于追踪 HTTP 客户端(OutgoingMessage)和 HTTP 请求(IncomingMessage)的耗时。对于 HTTP 客户端,它表示从发起请求到接收响应的时间间隔;对于 HTTP 请求,它表示从接收到请求到发送响应的时间间隔:
🌐 The following example is used to trace the time spent by HTTP client
(OutgoingMessage) and HTTP request (IncomingMessage). For HTTP client,
it means the time interval between starting the request and receiving the
response, and for HTTP request, it means the time interval between receiving
the request and sending the response:
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}`);
});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)所耗费的时间#>
🌐 Measuring how long the net.connect (only for TCP) takes when the connection is successful
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);
});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 花费的时间#>
🌐 Measuring how long the DNS takes when the request is successful
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');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');