perf_hooks 性能钩子
History
稳定性:2 - 稳定
本模块提供了 W3C 的一个子集的实现, Web 性能 API 以及针对 Node.js 特定性能测量的额外 API。
Node.js 支持以下 Web 性能 API:
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
performance.clearMarks();
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');
performance.mark('A');
doSomeLongRunningProcess(() => {
performance.measure('A to Now', 'A');
performance.mark('B');
performance.measure('A to B', 'A', 'B');
});一个可用于从当前
Node.js 实例收集性能指标的对象。它类似于浏览器中的 window.performance。
performance.clearMarks(name?): void<string>如果未提供 name,则从
性能时间线中移除所有 PerformanceMark 对象;如果提供了 name,则仅移除指定的标记。
performance.clearMeasures(name?): void<string>如果未提供 name,则从
性能时间线中移除所有 PerformanceMeasure 对象;如果提供了 name,则仅移除指定的测量。
performance.clearResourceTimings
History
此方法必须使用 performance 对象作为 接收者来调用。
performance.clearResourceTimings(name?): void<string>如果未提供 name,则从
资源时间线中移除所有 PerformanceResourceTiming 对象;如果提供了 name,则仅移除指定的资源。
performance.eventLoopUtilization
History
新增了 perf_hooks.eventLoopUtilization 别名。
performance.eventLoopUtilization(utilization1?, utilization2?): void这是 perf_hooks.eventLoopUtilization() 的别名。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
performance.getEntries(): void- 返回:
<PerformanceEntry>[]
返回一个 PerformanceEntry 对象列表,其时间顺序以
performanceEntry.startTime 为准。如果你只关心
某些类型或具有某些名称的性能条目,请参阅
performance.getEntriesByType() 和 performance.getEntriesByName()。
performance.getEntriesByName(name, type?): void返回一个 PerformanceEntry 对象列表,其时间顺序以
performanceEntry.startTime 为准,其中 performanceEntry.name
等于 name,并且可选地,performanceEntry.entryType 等于
type。
performance.getEntriesByType(type): void<string>返回一个 PerformanceEntry 对象列表,其时间顺序以
performanceEntry.startTime 为准,其中 performanceEntry.entryType
等于 type。
performance.mark(name, options?): void在性能时间线中创建一个新的 PerformanceMark 条目。
PerformanceMark 是 PerformanceEntry 的子类,其
performanceEntry.entryType 始终为 'mark',其
performanceEntry.duration 始终为 0。性能标记用于
标记性能时间线中特定的重要时刻。
创建的 PerformanceMark 条目会被放入全局性能时间线,
并且可以通过 performance.getEntries、
performance.getEntriesByName 和 performance.getEntriesByType 查询。当
执行观察时,应使用 performance.clearMarks 从全局
性能时间线中手动清除这些条目。
performance.markResourceTiming
History
新增了 bodyInfo、responseStatus 和 deliveryType 参数。
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus, deliveryType?): void此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
在资源时间线中创建一个新的 PerformanceResourceTiming 条目。
PerformanceResourceTiming 是 PerformanceEntry 的子类,其
performanceEntry.entryType 始终为 'resource'。性能资源
用于标记资源时间线中的时刻。
创建的 PerformanceMark 条目会被放入全局资源时间线,
并且可以通过 performance.getEntries、
performance.getEntriesByName 和 performance.getEntriesByType 查询。当
执行观察时,应使用 performance.clearResourceTimings 从全局
性能时间线中手动清除这些条目。
performance.measure(name, startMarkOrOptions?, endMark?): void在性能时间线中创建一个新的 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 从全局
性能时间线中手动清除这些条目。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
PerformanceNodeTiming 类的一个实例,它为
特定的 Node.js 运行里程碑提供性能指标。
performance.now(): void- 返回:
<number>
返回当前高分辨率毫秒时间戳,其中 0 表示
当前 node 进程的启动时刻。
performance.setResourceTimingBufferSize
History
此方法必须使用 performance 对象作为 接收者来调用。
performance.setResourceTimingBufferSize(maxSize): void将全局性能资源计时缓冲区大小设置为指定数量的 "resource" 类型性能条目对象。
默认情况下,最大缓冲区大小为 250。
- 类型:
<number>
timeOrigin 指定了高分辨率毫秒时间戳,
即当前 node 进程在 Unix 时间中的启动时刻。
performance.timerify(fn, options?): void<Function><Object><RecordableHistogram>perf_hooks.createHistogram()
创建的直方图对象,它将以
纳秒为单位记录运行时持续时间。这是 perf_hooks.timerify() 的别名。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
performance.toJSON(): void一个作为 performance 对象 JSON 表示的对象。它
类似于浏览器中的 window.performance.toJSON。
事件:'resourcetimingbufferfull'
History
当全局性能资源计时缓冲区已满时,会触发
'resourcetimingbufferfull' 事件。使用
performance.setResourceTimingBufferSize() 调整资源计时缓冲区大小,或使用
performance.clearResourceTimings() 在事件监听器中清除缓冲区,以允许更多条目
被添加到性能时间线缓冲区。
类:PerformanceEntry
History
此类的构造函数不直接向用户暴露。
performanceEntry.duration
History
此属性获取器必须使用 PerformanceEntry 对象作为接收者来调用。
- 类型:
<number>
此条目经过的总毫秒数。此值 并非对所有性能条目类型都有意义。
performanceEntry.entryType
History
此属性获取器必须使用 PerformanceEntry 对象作为接收者来调用。
- 类型:
<string>
性能条目的类型。它可以是以下之一:
'dns'(仅限 Node.js)'function'(仅限 Node.js)'gc'(仅限 Node.js)'http2'(仅限 Node.js)'http'(仅限 Node.js)'mark'(在 Web 上可用)'measure'(在 Web 上可用)'net'(仅限 Node.js)'node'(仅限 Node.js)'resource'(在 Web 上可用)
- 类型:
<string>
性能条目的名称。
performanceEntry.startTime
History
此属性获取器必须使用 PerformanceEntry 对象作为接收者来调用。
- 类型:
<number>
标记该性能条目开始时间的高分辨率毫秒 时间戳。
类:PerformanceMark
History
公开通过 Performance.mark() 方法创建的标记。
- 类型:
<any>
使用 Performance.mark() 方法创建时指定的额外详情。
类:PerformanceMeasure
History
公开通过 Performance.measure() 方法创建的测量。
此类的构造函数不直接向用户暴露。
performanceMeasure.detail
History
此属性获取器必须使用 PerformanceMeasure 对象作为接收者来调用。
- 类型:
<any>
使用 Performance.measure() 方法创建时指定的额外详情。
类:PerformanceNodeEntry
History
此类是 Node.js 的扩展。在 Web 浏览器中不可用。
提供详细的 Node.js 计时数据。
此类的构造函数不直接向用户暴露。
performanceNodeEntry.detail
History
此属性获取器必须使用 PerformanceNodeEntry 对象作为接收者来调用。
- 类型:
<any>
特定于 entryType 的额外详情。
performanceNodeEntry.flags
History
运行时已弃用。现在当 entryType 为 'gc' 时 移至 detail 属性。
稳定性:0 - 已弃用:改用
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
History
运行时已弃用。现在当 entryType 为 'gc' 时 移至 detail 属性。
稳定性:0 - 已弃用:改用
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_MINOR_MARK_SWEEPperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
当 performanceEntry.type 等于 'gc' 时,
performanceNodeEntry.detail 属性将是一个具有两个属性的 <Object>:
<number><number>当 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>。
这可能会增加额外的内存开销,应仅用于 诊断目的,默认情况下不要在生产环境中开启。
当 performanceEntry.type 等于 'http2' 时,
performanceNodeEntry.detail 属性将是一个包含
额外性能信息的 <Object>。
如果 performanceEntry.name 等于 Http2Stream,则 detail
将包含以下属性:
<number>Http2Stream
接收的
DATA
帧字节数。<number>Http2Stream
发送的
DATA
帧字节数。<number>Http2Stream
的标识符。<number>PerformanceEntry
的
startTime
与接收到第一个
DATA
帧之间经过的毫秒数。<number>PerformanceEntry
的
startTime
与发送第一个
DATA
帧之间经过的毫秒数。<number>PerformanceEntry
的
startTime
与接收到第一个标头之间经过的毫秒数。如果 performanceEntry.name 等于 Http2Session,则 detail 将
包含以下属性:
<number>Http2Session
接收的字节数。<number>Http2Session
发送的字节数。<number>Http2Session
接收的
HTTP/2 帧数量。<number>Http2Session
发送的 HTTP/2 帧数量。<number>Http2Session
生命周期内
同时打开的最大流数量。<number>PING
帧到
接收到其确认之间经过的毫秒数。仅当
已在
Http2Session
上发送过
PING
帧时才存在。<number>Http2Stream
实例的
平均持续时间(以毫秒为单位)。<number>Http2Session
处理的
Http2Stream
实例数量。<string>'server'
或
'client'
,用于标识
Http2Session
的类型。当 performanceEntry.type 等于 'function' 时,
performanceNodeEntry.detail 属性将是一个 <Array>,列出
被计时函数的输入参数。
当 performanceEntry.type 等于 'net' 时,
performanceNodeEntry.detail 属性将是一个包含
额外信息的 <Object>。
如果 performanceEntry.name 等于 connect,则 detail
将包含以下属性:host、port。
当 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
History
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
提供 Node.js 自身的计时详情。此类的构造函数 不向用户公开。
- 类型:
<number>
Node.js 进程完成引导时的高精度毫秒时间戳。 如果引导尚未完成,则该属性的 值为 -1。
- 类型:
<number>
高精度毫秒时间戳,表示 Node.js 环境 初始化的时刻。
- 类型:
<number>
事件循环在其事件提供程序(例如 epoll_wait)
中处于空闲状态时长的高精度毫秒时间戳。
此值不考虑 CPU 使用情况。如果事件循环尚未
启动(例如在主脚本的第一个 tick 中),则该属性的
值为 0。
- 类型:
<number>
Node.js 事件循环退出时的高精度毫秒时间戳。
如果事件循环尚未退出,则该属性的值为 -1。
只有在 'exit' 事件的处理程序中,它的值才可能不为 -1。
- 类型:
<number>
Node.js 事件循环启动时的高精度毫秒时间戳。 如果事件循环尚未启动(例如在主脚本的第一个 tick 中), 则该属性的值为 -1。
- 类型:
<number>
高精度毫秒时间戳,表示 Node.js 进程 初始化的时刻。
- 类型:
<Object>Attributes
这是对 uv_metrics_info 函数的封装。
它返回当前的事件循环指标集合。
这些值在 Number.MAX_SAFE_INTEGER 范围内是精确的。可以使用
performanceNodeTiming.uvMetricsInfoBigInt 来获取 libuv 报告的
完整 64 位值。
建议在使用 setImmediate 调度执行的函数内部使用此属性,
以避免在当前循环迭代中所有已调度的操作完成之前
收集指标。
const { performance } = require('node:perf_hooks');
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfo);
});- 类型:
<Object>Attributes
与 performanceNodeTiming.uvMetricsInfo 相同,不同之处在于这些值是
承载 libuv 报告的完整 64 位范围的 <bigint>。
由于 JSON.stringify() 无法序列化 <bigint> 值,因此此属性
不可枚举,也不会包含在 performanceNodeTiming.toJSON() 的
输出中。例如,通过展开 performance.nodeTiming 的可枚举属性
创建的副本仍可序列化。
const { performance } = require('node:perf_hooks');
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfoBigInt);
});- 类型:
<number>
高精度毫秒时间戳,表示 V8 平台 初始化的时刻。
类:PerformanceResourceTiming
History
提供有关加载应用程序资源方面的 详细网络计时数据。
此类的构造函数不直接向用户公开。
performanceResourceTiming.workerStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
恰在分派 fetch 请求之前的高精度毫秒时间戳。
如果资源未被 worker 拦截,则该属性
始终返回 0。
performanceResourceTiming.redirectStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示发起重定向的 fetch 的开始时间的 高精度毫秒时间戳。
performanceResourceTiming.redirectEnd
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
在收到最后一次重定向响应的最后一个字节后 立即创建的高精度毫秒时间戳。
performanceResourceTiming.fetchStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
Node.js 开始获取资源之前的 高精度毫秒时间戳。
performanceResourceTiming.domainLookupStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
Node.js 开始对资源进行域名查找之前的 高精度毫秒时间戳。
performanceResourceTiming.domainLookupEnd
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 刚完成对资源的域名查找时的 高精度毫秒时间戳。
performanceResourceTiming.connectStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 开始建立与服务器连接以 获取资源之前那一刻的 高精度毫秒时间戳。
performanceResourceTiming.connectEnd
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 完成建立与服务器的连接以 获取资源之后那一刻的 高精度毫秒时间戳。
performanceResourceTiming.secureConnectionStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 开始握手过程以保护 当前连接之前那一刻的高精度毫秒时间戳。
performanceResourceTiming.requestStart
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 收到来自服务器的响应的 第一个字节之前那一刻的高精度毫秒时间戳。
- 类型:
<number>
表示 Node.js 收到最终响应的第一个字节 (而非临时响应)之后那一刻的 高精度毫秒时间戳。
- 类型:
<number>
表示 Node.js 收到第一个临时响应的第一个字节
(例如 103 Early Hints 响应)之后那一刻的
高精度毫秒时间戳。
performanceResourceTiming.responseStart
History
当 firstInterimResponseStart 非零时, 此属性现在返回该值。
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 收到来自服务器的响应的
第一个字节之后那一刻的高精度毫秒时间戳。
当 firstInterimResponseStart 非零时为此值,
否则为 finalResponseHeadersStart。
performanceResourceTiming.responseEnd
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
表示 Node.js 收到资源的最后一个字节后, 或传输连接关闭前(以先发生者为准)那一刻的 高精度毫秒时间戳。
performanceResourceTiming.transferSize
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
一个数字,表示所获取资源的大小(以八位字节为单位)。 该大小包括响应头字段和响应负载主体。
performanceResourceTiming.encodedBodySize
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
一个数字,表示从获取(HTTP 或缓存)中收到的 负载主体大小(以八位字节为单位),此时尚未移除 任何已应用的内容编码。
performanceResourceTiming.decodedBodySize
History
此属性的 getter 必须以 PerformanceResourceTiming 对象作为接收者来调用。
- 类型:
<number>
一个数字,表示从获取(HTTP 或缓存)中收到的 消息主体大小(以八位字节为单位),此时已移除 任何已应用的内容编码。
- 类型:
<string>
资源的渲染阻塞状态。它可以是 'blocking' 或 'non-blocking'。
- 类型:
<string>
所获取资源内容的最小化 MIME 类型, 如果无法确定则为空字符串。
- 类型:
<string>
所获取资源的内容编码,例如 'gzip' 或 'br'。
performanceResourceTiming.toJSON
History
此方法必须以 PerformanceResourceTiming 对象作为接收者来调用。
performanceResourceTiming.toJSON(): void返回一个 object,它是
PerformanceResourceTiming 对象的 JSON 表示。
类:PerformanceObserver
History
- 类型:
<string>[]
获取支持的类型。
PerformanceObserver Constructor
History
向 callback 参数传递无效的回调现在会抛出 ERR_INVALID_ARG_TYPE 而不是 ERR_INVALID_CALLBACK。
new PerformanceObserver(callback): void<Function><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');由于 PerformanceObserver 实例会引入额外的性能开销,
因此不应让实例无限期地保持订阅通知的状态。
用户应在不再需要观察者时尽快
断开连接。
当 PerformanceObserver 收到有关新
PerformanceEntry 实例的通知时,会调用 callback。
该回调接收一个 PerformanceObserverEntryList 实例和对
PerformanceObserver 的引用。
performanceObserver.disconnect(): void断开 PerformanceObserver 实例与所有通知的连接。
performanceObserver.observe
History
已更新以符合性能时间线第 2 级规范。重新添加了 buffered 选项。
已更新以符合用户计时第 3 级规范。移除了 buffered 选项。
performanceObserver.observe(options): void<Object><string><PerformanceEntry>
类型。如果已指定
entryTypes
,则不得提供此选项。<string><PerformanceEntry>
实例的类型。如果未提供,
则会抛出错误。<boolean>PerformanceEntry
缓冲条目的列表调用观察者回调。如果为 false,则仅将
在该时间点之后创建的
PerformanceEntry
发送给
观察者回调。
默认值:
false
。订阅 <PerformanceObserver> 实例,以接收由 options.entryTypes
或 options.type 标识的新 <PerformanceEntry> 实例的
通知:
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((list, observer) => {
// 异步调用一次。`list` 包含三个条目。
});
obs.observe({ type: 'mark' });
for (let n = 0; n < 3; n++)
performance.mark(`test${n}`);performanceObserver.takeRecords(): void- 返回:
<PerformanceEntry>[] 性能观察者中当前存储的条目列表,并将其清空。
类:PerformanceObserverEntryList
History
PerformanceObserverEntryList 类用于提供对传递给
PerformanceObserver 的 PerformanceEntry 实例的访问。
此类的构造函数不向用户公开。
performanceObserverEntryList.getEntries(): void- 返回:
<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');performanceObserverEntryList.getEntriesByName(name, type?): void按 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');performanceObserverEntryList.getEntriesByType(type): void<string>返回按时间顺序排列的 PerformanceEntry 对象列表,
该顺序依据 performanceEntry.startTime,且其 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');perf_hooks.createHistogram(options?): void<Object><number>1
到
5
之间的数字。
默认值:
3
。<number>histogram.ewmaMean
和
histogram.ewmaStddev
访问。经过
halfLife
次记录后,某个值的影响会衰减到 50%。
默认值:
0
(禁用)。<number>halfLife
一起设置时,
直方图会跟踪超过该阈值的值的平滑错误率,
可通过
histogram.ewmaErrorRate
和
histogram.burnRate()
访问。
默认值:
0
(禁用)。返回一个 <RecordableHistogram>。
perf_hooks.createSlidingWindowHistogram(options): void<Object><number>1
到
1024
之间的整数。<number>1
到
18_446_744_073_709
之间的整数。必须指定
chunkDuration
和
recordsPerChunk
中的恰好一个。<number>record()
调用次数。
必须为
1
到
Number.MAX_SAFE_INTEGER
之间的整数。
必须指定
chunkDuration
和
recordsPerChunk
中的恰好一个。<number>1
到
5
之间的整数。
默认值:
3
。创建一个 {SlidingWindowHistogram},保留最新的 chunks 个直方图
块。轮换是惰性的,不会创建定时器。基于时间的轮换在
调用 record() 或 snapshot() 时进行计算。基于计数的轮换在
调用 record() 时进行计算。
构造时会分配一个直方图块。其他块会惰性分配。
窗口使用的最大原生内存随 chunks 以及 lowest、highest 和
figures 直方图选项而变化。
窗口边界具有块级精度。对于持续时间为 D 的 N 个块,
记录的值会保留 (N - 1) * D 到 N * D 毫秒。
基于计数的窗口一旦被填满,会保留 (N - 1) * C + 1 到
N * C 次记录尝试,其中 C 是
recordsPerChunk。超过 highest 的记录尝试在确定
基于计数的轮换时会被计入。
const { createSlidingWindowHistogram } = require('node:perf_hooks');
const window = createSlidingWindowHistogram({
chunks: 6,
chunkDuration: 10_000,
});
window.record(20_000_000);
// 将当前窗口具体化为独立的 Histogram。
const snapshot = window.snapshot();
console.log(snapshot.percentile(99));perf_hooks.importHistogram(data): void<Uint8Array>histogram.export()
.从 CBOR 编码的 Uint8Array 重建直方图。返回的
直方图是完整的 <RecordableHistogram>,所有桶数据、配置和
EWMA 状态均已恢复。可以将新值记录到其中。
由 histogram.export() 生成的任何格式版本的数据都可以
导入。有关详情,请参见 直方图导出格式兼容性。
const { createHistogram, importHistogram } = require('node:perf_hooks');
const h = createHistogram();
for (let i = 1; i <= 1000; i++) h.record(i);
// 序列化并重建
const data = h.export();
const h2 = importHistogram(data);
console.log(h2.count); // 1000
console.log(h2.percentile(99)); // Same as h.percentile(99)perf_hooks.eventLoopUtilization(utilization1?, utilization2?): voideventLoopUtilization() 函数返回一个对象,其中包含事件循环的
累计持续时间,期间事件循环既空闲又活跃,以高分辨率毫秒计时器表示。
utilization 值是计算得出的
事件循环利用率(ELU)。
如果主线程上的引导尚未完成,则这些属性的值为 0。ELU 在
工作线程 上立即可用,因为引导发生在
事件循环内部。
utilization1 和 utilization2 都是可选参数。
如果传入了 utilization1,则计算当前调用的 active 与 idle
时间之间的差值以及相应的 utilization 值,
并将其返回(类似于 process.hrtime())。
如果同时传入了 utilization1 和 utilization2,则计算
这两个参数之间的差值。这是一个便捷的选项,因为与
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);
});尽管运行此脚本时 CPU 大部分时间处于空闲状态,但 utilization 的值为
1。这是因为调用
child_process.spawnSync() 会阻塞事件循环继续运行。
传入用户定义的对象而不是上一次调用 eventLoopUtilization()
的结果将导致未定义行为。不能保证返回值
反映事件循环的任何正确状态。
perf_hooks.monitorEventLoopDelay(options?): void<Object>此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
创建一个直方图对象,用于采样并报告一段时间内的事件循环延迟。 延迟将以纳秒为单位报告。
默认情况下,直方图由定时器使用配置的
resolution 进行更新。当 samplePerIteration 为 true 时,每次
事件循环迭代使用 uv_prepare_t 和 uv_check_t 钩子采样一次。在该模式下,
当应用程序空闲时,直方图不会使循环保持活动状态或强制额外的
迭代。
两种采样模式会产生显著不同的结果,不应
直接进行比较。
lowest、highest 和 figures 选项对直方图的配置与
perf_hooks.createHistogram() 相同。lowest 必须大于 0,
因为事件循环延迟不可能为零:事件循环有
最小的开销,且测量本身依赖于事件循环的运转。
大于 highest 的延迟不会被记录,而是由
histogram.exceeds 计数。使用基于间隔的采样时,每个样本
都包含 resolution,因此 highest 应远高于
resolution * 1e6。直方图的内存使用取决于这些选项,而不是
样本的数量。
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// 做一些操作。
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?): void<Function><Object><RecordableHistogram>perf_hooks.createHistogram()
创建的直方图对象,将记录运行时持续时间,
以纳秒为单位。此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
将一个函数包装在一个新函数中,该新函数用于测量
被包装函数的运行时间。必须订阅 PerformanceObserver 的 'function'
事件类型,才能访问计时详情。
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'] });
// 将创建一个性能时间线条目
wrapped();如果被包装的函数返回一个 promise,则会附加一个 finally 处理程序 到该 promise 上,并在 finally 处理程序被调用时 报告持续时间。
类:Histogram
History
histogram.burnRate(sloTarget): void<number>0.999
表示 99.9% 的 SLO。返回 SLO 消耗率:ewmaErrorRate / (1 - sloTarget)。消耗率为 1
表示错误预算将在 SLO 窗口内恰好耗尽。
消耗率大于 1 表示其消耗速度快于允许的速度。
要求直方图在创建时同时设置了 halfLife 和
threshold 选项。
const { createHistogram } = require('node:perf_hooks');
// 使用 200ms 的 SLO 阈值、100 个样本的半衰期跟踪延迟
const h = createHistogram({ halfLife: 100, threshold: 200_000_000 });
// ... 记录延迟值 ...
// 对照 99.9% 的 SLO 检查消耗率
const rate = h.burnRate(0.999);
if (rate > 1) {
console.log(`SLO burn rate: ${rate.toFixed(2)}x — error budget depleting`);
}- 类型:
<number>
直方图记录的样本数。
- 类型:
<bigint>
直方图记录的样本数。
histogram.ccdf(value): void<number>返回给定值的互补累积分布函数(CCDF)值,
表示记录的值将超过 value 的概率。
等同于 1 - histogram.cdf(value)。
histogram.cdf(value): void<number>返回给定值的累积分布函数(CDF)值,
表示记录的值小于或等于 value 的概率。
这是以下操作的逆运算:
histogram.percentile().
histogram.cliffsD(other): void<Histogram>计算 Cliff's delta 统计量,一种非参数效应量度量。返回
来自此直方图的随机值超过来自 other 的随机值的概率,
减去相反的概率。值为 1 表示此直方图中的每个值
都超过 other 中的每个值;-1 表示
相反;0 表示两个方向都没有倾向。
histogram.cohensD(other): void<Histogram>计算 Cohen's d 效应量,即使用合并标准差计算的
此直方图与 other 的均值之间的标准化差异。
正值表示此直方图的均值更高。按照惯例,
|d| < 0.2 为小效应,0.5 为中等效应,0.8 及以上为大效应。
两个直方图都必须至少有 2 个记录值;否则返回 0。
histogram.countAt(value): void<number>返回落在给定值的等效值范围内的 记录值的数量。
histogram.diff(other): void<Histogram>返回一个新的 <Histogram>,其中包含拍摄 other 之后
此直方图中记录的值。两个直方图都不会改变。要获取每个
间隔内记录的值而无需调用 reset(),请从快照计算每个差值,
并将该快照保留为下一个间隔的基线:
const { monitorEventLoopDelay } = require('node:perf_hooks');
const histogram = monitorEventLoopDelay();
histogram.enable();
let previous = histogram.snapshot();
setInterval(() => {
const current = histogram.snapshot();
// 重置后,使用自重置以来记录的所有内容。
const delta = current.resetCount === previous.resetCount ?
current.diff(previous) : current;
console.log(delta.percentile(99));
previous = current;
}, 10_000);返回的直方图的 count、exceeds 和桶计数是两个直方图之间的
差值。它的 min 和 max 根据差值的桶计算,
它没有 EWMA 状态,其 resetCount 为
0.
此方法会抛出:
ERR_INVALID_ARG_VALUE,如果other的lowest、highest或figures配置不同。ERR_INVALID_STATE,如果自拍摄other以来从此直方图中 移除了值,即两个直方图的resetCount不同时。ERR_INVALID_ARG_VALUE,如果other包含此直方图中没有的值, 例如因为直方图的传入顺序错误。
- 类型:
<number>
由于超过直方图的最高可记录值而未被记录的 值的数量。
- 类型:
<bigint>
由于超过直方图的最高可记录值而未被记录的 值的数量。
histogram.export(): void- 返回:
<Uint8Array>
将直方图序列化为 CBOR 编码的(RFC 8949)Uint8Array,
适用于传输或持久化存储。编码使用桶计数的
增量编码稀疏表示,因此输出大小
随不同记录值的数量而扩展,而不是随桶的总数
扩展。
输出包括所有直方图配置、桶数据和 EWMA
状态(启用时)。可以使用以下方法将其重建为新的直方图:
perf_hooks.importHistogram().
CBOR 有效载荷是一个带有整数键的映射:
| 键 | 类型 | 字段 |
|---|---|---|
| 0 | uint | 格式版本(当前为 2) |
| 1 | uint | 最低可辨别值 |
| 2 | uint | 最高可追踪值 |
| 3 | uint | 有效数字位数 |
| 4 | uint | 总计数 |
| 5 | uint | 最小值 |
| 6 | uint | 最大值 |
| 7 | uint | 归一化索引偏移 |
| 8 | float64 | 转换比率 |
| 9 | uint | 计数数组长度 |
| 10 | array | 增量编码的稀疏计数 [delta, c, ...] |
| 11 | map | EWMA 状态(禁用时省略) |
任何标准的 CBOR 解码器都可以解析该输出。
perf_hooks.importHistogram() 接受 histogram.export() 曾产生的
所有格式版本:
- 版本 1 由 Node.js v26.9.0 产生。带有版本 1 键或 没有版本键的数据会按原始语义导入:上面未列出的 键会被拒绝。
- 版本 2 的布局与版本 1 相同。无法识别的键 会被忽略,因此更高版本的 Node.js 可以在不改变版本的情况下 向版本 2 数据添加字段,且数据仍可导入。
具有任何其他版本的数据会被拒绝。
当缺少总计数、最小值或最大值时,会从桶计数中推导出来。 存在的总计数必须与桶计数匹配。
- 类型:
<number>
记录值的指数加权移动平均值。仅当
直方图创建时设置了大于 0 的 halfLife 选项时才生效。
当 EWMA 被禁用或没有记录任何值时,返回 0。
- 类型:
<number>
指数加权移动标准差。仅当直方图创建时设置了
大于 0 的 halfLife 选项时才生效。当 EWMA 被禁用或
没有记录任何值时,返回 0。
- 类型:
<number>
记录值超过所配置的 threshold 的 EWMA 平滑概率。
仅当直方图创建时同时设置了 halfLife 和
threshold 选项时才生效。未启用或没有记录任何值时
返回 0。
histogram.ksTest(other): void<Histogram>计算 Kolmogorov-Smirnov 检验统计量,比较此直方图的
分布与 other。值为 0 表示分布相同;
接近 1 的值表示分布完全不相交。通过比较前后直方图,
可用于检测性能回归。
- 类型:
<number>
记录值的超额峰度。衡量分布尾部相对于 正态分布的厚重程度。正值表示尾部更重 (更极端的离群值);负值表示 尾部更轻。
histogram.linearBuckets(stepSize): void<number>返回重新分桶为等间距区间的直方图数据,
区间大小为 stepSize。可用于可视化和导出。
histogram.logBuckets(firstBucket, base): void返回经过重新分桶的直方图数据,各桶采用对数间隔,
其中每个桶的宽度乘以 base。
适用于可视化和导出。
histogram.mannWhitneyTest(other): void<Histogram>执行 Mann-Whitney U 检验,比较此直方图是否倾向于
产生比 other 更大或更小的值。与 welchTest() 不同,这是一种
非参数检验,它不对
分布的形状作任何假设。p 值使用带并列校正的
正态近似计算。
- 类型:
<number>
记录到的最大事件循环延迟。
- 类型:
<bigint>
记录到的最大事件循环延迟。
- 类型:
<number>
记录到的事件循环延迟的平均值。
histogram.meanCI(options?): void使用 Student's t 分布和样本标准误差返回均值的双侧 置信区间。置信水平越高,区间 越宽。此区间假设样本相互独立 且近似服从正态分布,不过这种近似在 样本量足够大时是稳健的。
结果反映直方图配置的精度,并基于其桶所表示的
值计算得出。当记录的值少于两个时,
lower 和 upper 为 NaN。当所有记录的值都相等时,
lower 和 upper 等于 mean。
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
for (let i = 1; i <= 100; i++) h.record(i);
const { mean, lower, upper } = h.meanCI();
console.log(`mean=${mean}, 95% CI=[${lower}, ${upper}]`);- 类型:
<number>
记录到的最小事件循环延迟。
- 类型:
<bigint>
记录到的最小事件循环延迟。
histogram.percentile(percentile): void<number>返回给定百分位数处的值。
histogram.percentileBigInt(percentile): void<number>返回给定百分位数处的值。
histogram.percentileCI(percentile, options?): void使用精确的二项式方法返回给定百分位数的置信区间。样本
越少,区间越宽,反映出
百分位数估计的不确定性越大。至少需要 2 个
记录值;少于 2 个时,lower 和 upper 将等于 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)- 类型:
<Map>
返回一个 Map 对象,详细描述累积的百分位数分布。
- 类型:
<Map>
返回一个 Map 对象,详细描述累积的百分位数分布。
histogram.percentilesAt(percentiles): void<number>返回指定百分位数处的值,通过对直方图数据进行一次
高效遍历计算得出。比多次调用
histogram.percentile() 更高效。
histogram.qrde(options?): void<Object><number>probabilities
同时使用。
默认值:
100
。<number>0
开头,并以
1
结尾。不能与
bins
同时使用。<string>'none'
、
'hdr'
或
'all'
。
默认值:
'hdr'
。<boolean>true
时,保留展开后的直方图快照,
供后续使用
cache: true
的调用复用。当直方图被修改时,
该快照失效。
默认值:
false
。<Float64Array><Float64Array><Float64Array><bigint><number><number><string>返回基于 Harrell-Davis 分位数估计器的分位数感知密度
估计。默认情况下,bins 生成等概率边界。
probabilities 选项可以改为将估计重点放在诸如
p90、p99、p99.9 和 p99.99 等区域。区间 i 的密度包含概率
质量 probabilities[i + 1] - probabilities[i]。调用该方法时
会对直方图进行快照。快照展开和估计在
libuv 线程池中计算。高度集中的 beta 权重使用二阶
渐近近似,以避免在样本量较大时
出现数值收敛损失。
将 cache 设置为 true 可避免在对未变化的直方图请求多个
估计时重复进行快照捕获和展开。保留的
快照占用的内存与已占用的 HDR 桶数量成正比,并在
下次修改直方图时释放。
QRDE 临时使用大约一个额外的 HDR 计数数组,外加每个
已占用桶 32 字节。使用 cache: true 时,展开后的每桶 32 字节的
快照会保持分配状态。以下估计使用 lowest: 1 和
highest: Number.MAX_SAFE_INTEGER,并排除了分配器和 JavaScript 对象
的开销:
figures | 直方图 | 最大展开快照 | 缓存未命中时 QRDE 峰值 |
|---|---|---|---|
| 1 | 6.3 KiB | 25 KiB | 31 KiB |
| 2 | 47 KiB | 188 KiB | 235 KiB |
| 3 | 352 KiB | 1.4 MiB | 1.7 MiB |
| 4 | 5.0 MiB | 20 MiB | 25 MiB |
| 5 | 37 MiB | 148 MiB | 185 MiB |
最大快照列假设每个可表示的桶都已占用。
较低的 highest 值可减小直方图和临时副本的大小。并发
调用若未命中缓存,则各自需要自己的临时副本和展开的
快照。
HDR 直方图将观测值聚合到等值桶中。
'hdr' 反量化模式将宽度大于一个单位的桶中的
重复值建模为桶分辨率上的连续均匀分布。这
减少了 HDR 量化引入的密度伪影,同时
将重复的单位分辨率值保留为点质量。'all' 模式还会
对重复的单位分辨率值进行反量化。使用 'none' 可
直接使用桶中点计算分组 Harrell-Davis 估计器。
空直方图会返回请求的 probabilities,但产生空的
quantiles 和 densities 数组。未反量化的区间如果其分位数
边界相等,则密度为无穷大。
histogram.reset(): void重置收集到的直方图数据并递增 histogram.resetCount。
- 类型:
<number>
通过 reset() 从该直方图中移除值的次数,
对于 <RecordableHistogram> 则是通过 subtract()。快照保留其
来源在创建时的 resetCount,因此比较两个
快照的 resetCount 可以判断来源在两者之间是否被重置。参见
histogram.diff().
- 类型:
<number>
记录值的偏度。衡量分布的 不对称性。正值表示右偏分布 (右侧尾部更长,常见于延迟数据);负值 表示左偏分布。
histogram.snapshot(): void- 返回:
<Histogram>
返回一个新的、独立的 <Histogram>,其中包含此直方图当前
状态的副本:其配置、记录值、exceeds 计数和 EWMA
状态。在此方法返回后记录到该直方图的值,以及后续
对 reset() 的调用,都不会改变返回的直方图。这为仍在
记录的直方图(例如已启用的 <ELDHistogram>)提供了稳定的视图。
不能向返回的直方图中记录值。创建快照会复制
每个桶,因此其时间和内存开销取决于直方图的
lowest、highest 和 figures 配置,而非
记录值的数量。
const { monitorEventLoopDelay } = require('node:perf_hooks');
const histogram = monitorEventLoopDelay();
histogram.enable();
setTimeout(() => {
const snapshot = histogram.snapshot();
console.log(snapshot.percentile(99));
histogram.disable();
}, 1000);- 类型:
<number>
记录到的事件循环延迟的标准差。
histogram.welchTest(other, options?): void执行 Welch t 检验,比较此直方图与 other 的均值。
p 值表示在原假设(两个分布具有
相同均值)下,观察到至少如此极端的差异的
概率。两个直方图都必须至少有 2 个记录值;
否则结果的 pValue 为 1、tStatistic 为 0。
一个记录事件循环延迟的 Histogram,由
perf_hooks.monitorEventLoopDelay().
histogram.disable(): void- 返回:
<boolean>
禁用事件循环延迟采样。如果采样已
停止则返回 true,如果本就已停止则返回 false。
histogram.enable(): void- 返回:
<boolean>
启用事件循环延迟采样。如果采样已
启动则返回 true,如果本就已启动则返回 false。
histogram[Symbol.dispose](): void当直方图被释放(dispose)时禁用事件循环延迟采样。
const { monitorEventLoopDelay } = require('node:perf_hooks');
{
using hist = monitorEventLoopDelay({ resolution: 20 });
hist.enable();
// 代码块退出时将禁用该直方图。
}<ELDHistogram> 实例可以通过 <MessagePort> 克隆。在接收端,
该直方图被克隆为普通的 <Histogram> 对象,不实现 enable() 和 disable() 方法。
类:RecordableHistogram extends Histogram
History
histogram.add(other): void<RecordableHistogram>将 other 中的值添加到此直方图。
histogram.record(val): void小于直方图 lowest 选项的值(包括 0)可能
彼此无法区分。
histogram.recordDelta(): void计算自上次调用 recordDelta() 以来经过的时间
(以纳秒为单位),并将该时长记录到直方图中。
histogram.recordCorrected(val, expectedInterval): void使用协调遗漏校正记录一个值。当系统停顿
导致无法及时记录时,此方法会在先前记录的值与 val 之间
按 expectedInterval 步长回填中间值。
这弥补了那些原本会低估延迟的
测量间隙。
histogram.subtract(other): void<RecordableHistogram>从直方图中减去 other 的值。两个直方图应具有
兼容的配置。会变为负数的桶计数
将被钳制为零。递增 histogram.resetCount。
类:SlidingWindowHistogram
History
将值记录到惰性轮转的直方图块环中。实例通过
perf_hooks.createSlidingWindowHistogram() 创建,不能直接
构造。SlidingWindowHistogram 不继承 <Histogram>;
调用 snapshot() 可将当前窗口具体化为 <Histogram>。
SlidingWindowHistogram 实例无法通过 <MessagePort> 克隆或传输。
<MessagePort>.
slidingWindowHistogram.record(val): void将 val 记录到当前块中。对于基于计数的窗口,每次到达
原生直方图的调用都计入轮转,包括超过
配置的 highest 值的值。
slidingWindowHistogram.reset(): void使当前窗口中的所有块失效。已分配的块在 重用时惰性重置。
slidingWindowHistogram.snapshot(): void- 返回:
<Histogram>
将当前窗口具体化为一个新的、独立的 <Histogram>。在此方法
返回后记录或过期的值不会改变返回的
直方图。具体化会分配一个直方图并合并每个保留的
块。
Histogram 类提供了统计分析方法来辅助
性能监控、SLO 强制实施和回归检测。
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
// 模拟右偏的延迟分布
for (let i = 0; i < 1000; i++) {
h.record(Math.ceil(Math.random() * 100));
}
// 添加一些异常值
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 tailsconst { createHistogram } = require('node:perf_hooks');
const latency = createHistogram();
// 记录请求延迟(以纳秒为单位)...
// "有多少请求在 100ms 内完成?"
const withinSLO = latency.cdf(100_000_000);
console.log(`${(withinSLO * 100).toFixed(1)}% of requests within SLO`);
// "有多少请求超过 500ms?"
const violating = latency.ccdf(500_000_000);
console.log(`${(violating * 100).toFixed(1)}% of requests violating SLO`);const { createHistogram } = require('node:perf_hooks');
// 使用 EWMA 跟踪延迟(半衰期为 100 个样本),并设置 200ms 的 SLO 阈值
const latency = createHistogram({
halfLife: 100,
threshold: 200_000_000, // 200ms in nanoseconds
});
// 记录请求延迟...
// 平滑后的错误率:超过阈值的概率
console.log(`Error rate: ${(latency.ewmaErrorRate * 100).toFixed(2)}%`);
// 相对于 99.9% SLO 的消耗率
// >1 表示错误预算的消耗速度快于允许的速度
const rate = latency.burnRate(0.999);
console.log(`Burn rate: ${rate.toFixed(2)}x`);
// EWMA 均值和标准差跟踪平滑后的延迟
console.log(`EWMA latency: ${latency.ewmaMean.toFixed(0)}ns`);
console.log(`EWMA stddev: ${latency.ewmaStddev.toFixed(0)}ns`);const { createHistogram } = require('node:perf_hooks');
const baseline = createHistogram();
const current = createHistogram();
// 记录基线和当前的延迟...
// D 统计量:0 = 完全相同,1 = 完全不同
const d = baseline.ksTest(current);
if (d > 0.1) {
console.log(`Possible regression detected (D=${d.toFixed(4)})`);
}const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
// 记录值...
// 一次遍历高效查询常用的监控百分位数
const p = h.percentilesAt([50, 75, 90, 95, 99, 99.9]);
console.log('p50:', p.get(50));
console.log('p99:', p.get(99));const { createHistogram } = require('node:perf_hooks');
const total = createHistogram();
const snapshot = createHistogram();
// 将值记录到 total 中...
// 定期创建快照以进行"上一时间间隔"分析:
snapshot.add(total);
// 稍后,创建新的快照并进行差异比较:
const newSnapshot = createHistogram();
newSnapshot.add(total);
newSnapshot.subtract(snapshot);
// newSnapshot 现在只包含自上次快照以来记录的值
console.log('Recent p99:', newSnapshot.percentile(99));const { createHistogram } = require('node:perf_hooks');
const baseline = createHistogram();
const candidate = createHistogram();
// 记录旧版本和新版本的操作速率...
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)})`);
}const { createHistogram } = require('node:perf_hooks');
const before = createHistogram();
const after = createHistogram();
// 记录变更前后的延迟...
const delta = before.cliffsD(after);
// delta > 0:变更前倾向于产生更大的值(改进)
// delta < 0:变更后倾向于产生更大的值(回归)
console.log(`Cliff's delta: ${delta.toFixed(4)}`);以下示例使用 异步钩子 和 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);以下示例测量 require() 操作加载
依赖项所需的时长:
import { performance, PerformanceObserver } from 'node:perf_hooks';
// 激活观察者
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');以下示例用于跟踪 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}`);
});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);
});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');