On this page

perf_hooks 性能钩子

History
Source Code: lib/perf_hooks.js

稳定性: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');
});
P

perf_hooks.performance

History

一个可用于从当前 Node.js 实例收集性能指标的对象。它类似于浏览器中的 window.performance。

performance.clearMarks(name?): void
Attributes

如果未提供 name,则从 性能时间线中移除所有 PerformanceMark 对象;如果提供了 name,则仅移除指定的标记。

performance.clearMeasures(name?): void
Attributes

如果未提供 name,则从 性能时间线中移除所有 PerformanceMeasure 对象;如果提供了 name,则仅移除指定的测量。

performance.clearResourceTimings(name?): void
Attributes

如果未提供 name,则从 资源时间线中移除所有 PerformanceResourceTiming 对象;如果提供了 name,则仅移除指定的资源。

performance.eventLoopUtilization(utilization1?, utilization2?): void
Attributes
utilization1:<Object>
上一次调用  eventLoopUtilization() 的结果。
utilization2:<Object>
上一次调用  eventLoopUtilization() 的结果,该调用早于 utilization1 。
active:<number>
utilization:<number>

这是 perf_hooks.eventLoopUtilization() 的别名。

此属性是 Node.js 的扩展。在 Web 浏览器中不可用。

performance.getEntries(): void

返回一个 PerformanceEntry 对象列表,其时间顺序以 performanceEntry.startTime 为准。如果你只关心 某些类型或具有某些名称的性能条目,请参阅 performance.getEntriesByType() 和 performance.getEntriesByName()。

performance.getEntriesByName(name, type?): void
Attributes

返回一个 PerformanceEntry 对象列表,其时间顺序以 performanceEntry.startTime 为准,其中 performanceEntry.name 等于 name,并且可选地,performanceEntry.entryType 等于 type。

performance.getEntriesByType(type): void
Attributes

返回一个 PerformanceEntry 对象列表,其时间顺序以 performanceEntry.startTime 为准,其中 performanceEntry.entryType 等于 type。

performance.mark(name, options?): void
Attributes
options:<Object>
detail:<any>
随标记包含的额外可选详情。
startTime:<number>
用作标记时间的可选时间戳。  默认值 : performance.now() 。

在性能时间线中创建一个新的 PerformanceMark 条目。 PerformanceMark 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'mark',其 performanceEntry.duration 始终为 0。性能标记用于 标记性能时间线中特定的重要时刻。

创建的 PerformanceMark 条目会被放入全局性能时间线, 并且可以通过 performance.getEntries、 performance.getEntriesByName 和 performance.getEntriesByType 查询。当 执行观察时,应使用 performance.clearMarks 从全局 性能时间线中手动清除这些条目。

performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus, deliveryType?): void
Attributes
requestedUrl:<string>
资源 URL
initiatorType:<string>
发起者名称,例如 'fetch'
global:<Object>
cacheMode:<string>
缓存模式必须是空字符串 ('') 或 'local'
responseStatus:<number>
响应的状态码
deliveryType:<string>
交付类型。  默认值: '' 。

此属性是 Node.js 的扩展。在 Web 浏览器中不可用。

在资源时间线中创建一个新的 PerformanceResourceTiming 条目。 PerformanceResourceTiming 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'resource'。性能资源 用于标记资源时间线中的时刻。

创建的 PerformanceMark 条目会被放入全局资源时间线, 并且可以通过 performance.getEntries、 performance.getEntriesByName 和 performance.getEntriesByType 查询。当 执行观察时,应使用 performance.clearResourceTimings 从全局 性能时间线中手动清除这些条目。

performance.measure(name, startMarkOrOptions?, endMark?): void
Attributes
startMarkOrOptions:<string> | <Object>
可选。
detail:<any>
随测量包含的额外可选详情。
duration:<number>
开始时间与结束时间之间的持续时间。
用作结束时间的时间戳,或用于 标识先前记录的标记的字符串。
用作开始时间的时间戳,或用于 标识先前记录的标记的字符串。
endMark:<string>
可选。如果  startMarkOrOptions  是一个 <Object> ,则必须省略该参数。

在性能时间线中创建一个新的 PerformanceMeasure 条目。 PerformanceMeasure 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'measure',其 performanceEntry.duration 测量自 startMark 和 endMark 以来经过的毫秒数。

startMark 参数可以标识_现有的_任何 PerformanceMark, 这些标记位于性能时间线中;或_可以_标识任何时间戳 属性,这些属性由 PerformanceNodeTiming 类提供。如果指定的 startMark 不存在,则抛出错误。

可选的 endMark 参数必须标识_现有的_任何 PerformanceMark, 这些标记位于性能时间线中,或 PerformanceNodeTiming 类提供的 任何时间戳属性。如果未传递参数,endMark 将为 performance.now(), 否则如果指定的 endMark 不存在,则将抛出 错误。

创建的 PerformanceMeasure 条目会被放入全局性能时间线, 并且可以通过 performance.getEntries、 performance.getEntriesByName 和 performance.getEntriesByType 查询。当 执行观察时,应使用 performance.clearMeasures 从全局 性能时间线中手动清除这些条目。

P

performance.nodeTiming

History

此属性是 Node.js 的扩展。在 Web 浏览器中不可用。

PerformanceNodeTiming 类的一个实例,它为 特定的 Node.js 运行里程碑提供性能指标。

performance.now(): void

返回当前高分辨率毫秒时间戳,其中 0 表示 当前 node 进程的启动时刻。

performance.setResourceTimingBufferSize(maxSize): void

将全局性能资源计时缓冲区大小设置为指定数量的 "resource" 类型性能条目对象。

默认情况下,最大缓冲区大小为 250。

P

performance.timeOrigin

History

timeOrigin 指定了高分辨率毫秒时间戳, 即当前 node 进程在 Unix 时间中的启动时刻。

performance.timerify(fn, options?): void
Attributes
options:<Object>
使用  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

此类的构造函数不直接向用户暴露。

此条目经过的总毫秒数。此值 并非对所有性能条目类型都有意义。

性能条目的类型。它可以是以下之一:

  • '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 上可用)

性能条目的名称。

标记该性能条目开始时间的高分辨率毫秒 时间戳。

类:PerformanceMark

History

公开通过 Performance.mark() 方法创建的标记。

使用 Performance.mark() 方法创建时指定的额外详情。

类:PerformanceMeasure

History

公开通过 Performance.measure() 方法创建的测量。

此类的构造函数不直接向用户暴露。

使用 Performance.measure() 方法创建时指定的额外详情。

类:PerformanceNodeEntry

History

此类是 Node.js 的扩展。在 Web 浏览器中不可用。

提供详细的 Node.js 计时数据。

此类的构造函数不直接向用户暴露。

特定于 entryType 的额外详情。

稳定性:0 - 已弃用:改用 performanceNodeEntry.detail。

当 performanceEntry.entryType 等于 'gc' 时,performance.flags 属性包含有关垃圾回收操作的额外信息。 该值可以是以下之一:

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

稳定性:0 - 已弃用:改用 performanceNodeEntry.detail。

当 performanceEntry.entryType 等于 'gc' 时,performance.kind 属性标识所发生的垃圾回收操作的类型。 该值可以是以下之一:

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

当 performanceEntry.type 等于 'gc' 时, performanceNodeEntry.detail 属性将是一个具有两个属性的 <Object>:

Attributes
以下之一:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR:
perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR:
perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR_MARK_SWEEP:
perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL:
perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB:
flags:<number>
以下之一:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE:

当 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 将包含以下属性:

Attributes
bytesRead:<number>
为此  Http2Stream 接收的 DATA 帧字节数。
bytesWritten:<number>
为此  Http2Stream 发送的 DATA 帧字节数。
关联的  Http2Stream 的标识符。
timeToFirstByte:<number>
PerformanceEntry 的 startTime 与接收到第一个 DATA 帧之间经过的毫秒数。
timeToFirstByteSent:<number>
PerformanceEntry 的 startTime 与发送第一个 DATA 帧之间经过的毫秒数。
timeToFirstHeader:<number>
PerformanceEntry 的 startTime 与接收到第一个标头之间经过的毫秒数。

如果 performanceEntry.name 等于 Http2Session,则 detail 将 包含以下属性:

Attributes
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 实例数量。
'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 自身的计时详情。此类的构造函数 不向用户公开。

P

performanceNodeTiming.bootstrapComplete

History

Node.js 进程完成引导时的高精度毫秒时间戳。 如果引导尚未完成,则该属性的 值为 -1。

P

performanceNodeTiming.environment

History

高精度毫秒时间戳,表示 Node.js 环境 初始化的时刻。

P

performanceNodeTiming.idleTime

History

事件循环在其事件提供程序(例如 epoll_wait) 中处于空闲状态时长的高精度毫秒时间戳。 此值不考虑 CPU 使用情况。如果事件循环尚未 启动(例如在主脚本的第一个 tick 中),则该属性的 值为 0。

P

performanceNodeTiming.loopExit

History

Node.js 事件循环退出时的高精度毫秒时间戳。 如果事件循环尚未退出,则该属性的值为 -1。 只有在 'exit' 事件的处理程序中,它的值才可能不为 -1。

P

performanceNodeTiming.loopStart

History

Node.js 事件循环启动时的高精度毫秒时间戳。 如果事件循环尚未启动(例如在主脚本的第一个 tick 中), 则该属性的值为 -1。

P

performanceNodeTiming.nodeStart

History

高精度毫秒时间戳,表示 Node.js 进程 初始化的时刻。

P

performanceNodeTiming.uvMetricsInfo

History
  • 类型:<Object>
    Attributes
    loopCount:<number>
    事件循环迭代的次数。
    events:<number>
    事件处理程序已处理的事件数量。
    eventsWaiting:<number>
    调用事件提供程序时等待处理的事件数量。

这是对 uv_metrics_info 函数的封装。 它返回当前的事件循环指标集合。

这些值在 Number.MAX_SAFE_INTEGER 范围内是精确的。可以使用 performanceNodeTiming.uvMetricsInfoBigInt 来获取 libuv 报告的 完整 64 位值。

建议在使用 setImmediate 调度执行的函数内部使用此属性, 以避免在当前循环迭代中所有已调度的操作完成之前 收集指标。

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

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

performanceNodeTiming.uvMetricsInfoBigInt

History
  • 类型:<Object>
    Attributes
    loopCount:<bigint>
    事件循环迭代的次数。
    events:<bigint>
    事件处理程序已处理的事件数量。
    eventsWaiting:<bigint>
    调用事件提供程序时等待处理的事件数量。

与 performanceNodeTiming.uvMetricsInfo 相同,不同之处在于这些值是 承载 libuv 报告的完整 64 位范围的 <bigint>。

由于 JSON.stringify() 无法序列化 <bigint> 值,因此此属性 不可枚举,也不会包含在 performanceNodeTiming.toJSON() 的 输出中。例如,通过展开 performance.nodeTiming 的可枚举属性 创建的副本仍可序列化。

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

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

performanceNodeTiming.v8Start

History

高精度毫秒时间戳,表示 V8 平台 初始化的时刻。

类:PerformanceResourceTiming

History

提供有关加载应用程序资源方面的 详细网络计时数据。

此类的构造函数不直接向用户公开。

恰在分派 fetch 请求之前的高精度毫秒时间戳。 如果资源未被 worker 拦截,则该属性 始终返回 0。

表示发起重定向的 fetch 的开始时间的 高精度毫秒时间戳。

在收到最后一次重定向响应的最后一个字节后 立即创建的高精度毫秒时间戳。

Node.js 开始获取资源之前的 高精度毫秒时间戳。

Node.js 开始对资源进行域名查找之前的 高精度毫秒时间戳。

表示 Node.js 刚完成对资源的域名查找时的 高精度毫秒时间戳。

表示 Node.js 开始建立与服务器连接以 获取资源之前那一刻的 高精度毫秒时间戳。

表示 Node.js 完成建立与服务器的连接以 获取资源之后那一刻的 高精度毫秒时间戳。

表示 Node.js 开始握手过程以保护 当前连接之前那一刻的高精度毫秒时间戳。

表示 Node.js 收到来自服务器的响应的 第一个字节之前那一刻的高精度毫秒时间戳。

表示 Node.js 收到最终响应的第一个字节 (而非临时响应)之后那一刻的 高精度毫秒时间戳。

表示 Node.js 收到第一个临时响应的第一个字节 (例如 103 Early Hints 响应)之后那一刻的 高精度毫秒时间戳。

表示 Node.js 收到来自服务器的响应的 第一个字节之后那一刻的高精度毫秒时间戳。 当 firstInterimResponseStart 非零时为此值, 否则为 finalResponseHeadersStart。

表示 Node.js 收到资源的最后一个字节后, 或传输连接关闭前(以先发生者为准)那一刻的 高精度毫秒时间戳。

一个数字,表示所获取资源的大小(以八位字节为单位)。 该大小包括响应头字段和响应负载主体。

一个数字,表示从获取(HTTP 或缓存)中收到的 负载主体大小(以八位字节为单位),此时尚未移除 任何已应用的内容编码。

一个数字,表示从获取(HTTP 或缓存)中收到的 消息主体大小(以八位字节为单位),此时已移除 任何已应用的内容编码。

P

performanceResourceTiming.renderBlockingStatus

History

资源的渲染阻塞状态。它可以是 'blocking' 或 'non-blocking'。

P

performanceResourceTiming.contentType

History

所获取资源内容的最小化 MIME 类型, 如果无法确定则为空字符串。

P

performanceResourceTiming.contentEncoding

History

所获取资源的内容编码,例如 'gzip' 或 'br'。

performanceResourceTiming.toJSON(): void

返回一个 object,它是 PerformanceResourceTiming 对象的 JSON 表示。

类:PerformanceObserver

History
P

PerformanceObserver.supportedEntryTypes

History

获取支持的类型。

new PerformanceObserver(callback): void
Attributes

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 的引用。

M

performanceObserver.disconnect

History
performanceObserver.disconnect(): void

断开 PerformanceObserver 实例与所有通知的连接。

performanceObserver.observe(options): void
Attributes
options:<Object>
单个 <PerformanceEntry> 类型。如果已指定  entryTypes ,则不得提供此选项。
entryTypes:<string>
[] 一个字符串数组,用于标识观察者感兴趣的 <PerformanceEntry> 实例的类型。如果未提供, 则会抛出错误。
buffered:<boolean>
如果为 true,则使用全局  PerformanceEntry 缓冲条目的列表调用观察者回调。如果为 false,则仅将 在该时间点之后创建的 PerformanceEntry 发送给 观察者回调。 默认值: false 。

订阅 <PerformanceObserver> 实例,以接收由 options.entryTypes 或 options.type 标识的新 <PerformanceEntry> 实例的 通知:

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

const obs = new PerformanceObserver((list, observer) => {
  // 异步调用一次。`list` 包含三个条目。
});
obs.observe({ type: 'mark' });

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

performanceObserver.takeRecords

History
performanceObserver.takeRecords(): void
  • 返回:<PerformanceEntry>[] 性能观察者中当前存储的条目列表,并将其清空。

类:PerformanceObserverEntryList

History

PerformanceObserverEntryList 类用于提供对传递给 PerformanceObserver 的 PerformanceEntry 实例的访问。 此类的构造函数不向用户公开。

M

performanceObserverEntryList.getEntries

History
performanceObserverEntryList.getEntries(): void

按 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');
M

performanceObserverEntryList.getEntriesByName

History
performanceObserverEntryList.getEntriesByName(name, type?): void
Attributes

按 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');
M

performanceObserverEntryList.getEntriesByType

History
performanceObserverEntryList.getEntriesByType(type): void
Attributes

返回按时间顺序排列的 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');
M

perf_hooks.createHistogram

History
perf_hooks.createHistogram(options?): void
Attributes
options:<Object>
最低可辨别值。必须为大于 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>。

M

perf_hooks.createSlidingWindowHistogram

History
perf_hooks.createSlidingWindowHistogram(options): void
Attributes
options:<Object>
chunks:<number>
保留的直方图块数。必须为  1 到 1024 之间的整数。
chunkDuration:<number>
每个块的持续时间(以毫秒为单位)。必须为  1 到 18_446_744_073_709 之间的整数。必须指定 chunkDuration 和 recordsPerChunk 中的恰好一个。
recordsPerChunk:<number>
分配给每个块的  record() 调用次数。 必须为 1 到 Number.MAX_SAFE_INTEGER 之间的整数。 必须指定 chunkDuration 和 recordsPerChunk 中的恰好一个。
最低可辨别值。必须为大于  0 的整数值。 默认值: 1 。
highest:<number> | <bigint>
最高可记录值。必须为整数值, 且大于或等于  lowest 的两倍。 默认值: Number.MAX_SAFE_INTEGER 。
figures:<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
Attributes
一个 CBOR 编码的直方图,之前由  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)
M

perf_hooks.eventLoopUtilization

History
perf_hooks.eventLoopUtilization(utilization1?, utilization2?): void
Attributes
utilization1:<Object>
上一次调用  eventLoopUtilization() .
utilization2:<Object>
在  utilization1 之前的上一次调用 eventLoopUtilization() 的结果。
active:<number>
utilization:<number>

eventLoopUtilization() 函数返回一个对象,其中包含事件循环的 累计持续时间,期间事件循环既空闲又活跃,以高分辨率毫秒计时器表示。 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
Attributes
options:<Object>
samplePerIteration:<boolean>
为  true 时,每次 事件循环迭代采样一次。 默认值: false 。
resolution:<number>
基于间隔的采样的采样率(以毫秒为单位)。 必须大于零。当  samplePerIteration 为 true 时, 此选项被忽略。 默认值: 10 。
最低可辨别延迟(以纳秒为单位)。必须为 大于  0 的整数值。 默认值: 当 samplePerIteration 为 true 时为 1 , 否则为 1000 。
highest:<number> | <bigint>
最高可记录延迟(以纳秒为单位)。 必须为大于或等于  lowest 两倍的整数值。 默认值: 2n ** 63n - 1n 。
figures:<number>
精度位数。必须为  1 到 5 之间的整数。 默认值: 3 。

此属性是 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));
M

perf_hooks.timerify

History
perf_hooks.timerify(fn, options?): void
Attributes
options:<Object>
使用  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
M

histogram.burnRate

History
histogram.burnRate(sloTarget): void
Attributes
sloTarget:<number>
SLO 目标,为 0 到 1 之间的分数 (不含端点)。例如, 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`);
}
P

histogram.count

History

直方图记录的样本数。

P

histogram.countBigInt

History

直方图记录的样本数。

M

histogram.ccdf

History
histogram.ccdf(value): void
Attributes
value:<number>
要查询的值。

返回给定值的互补累积分布函数(CCDF)值, 表示记录的值将超过 value 的概率。 等同于 1 - histogram.cdf(value)。

M

histogram.cdf

History
histogram.cdf(value): void
Attributes
value:<number>
要查询的值。

返回给定值的累积分布函数(CDF)值, 表示记录的值小于或等于 value 的概率。 这是以下操作的逆运算: histogram.percentile().

M

histogram.cliffsD

History
histogram.cliffsD(other): void
Attributes
要比较的直方图。

计算 Cliff's delta 统计量,一种非参数效应量度量。返回 来自此直方图的随机值超过来自 other 的随机值的概率, 减去相反的概率。值为 1 表示此直方图中的每个值 都超过 other 中的每个值;-1 表示 相反;0 表示两个方向都没有倾向。

M

histogram.cohensD

History
histogram.cohensD(other): void
Attributes
要比较的直方图。

计算 Cohen's d 效应量,即使用合并标准差计算的 此直方图与 other 的均值之间的标准化差异。 正值表示此直方图的均值更高。按照惯例, |d| < 0.2 为小效应,0.5 为中等效应,0.8 及以上为大效应。 两个直方图都必须至少有 2 个记录值;否则返回 0。

M

histogram.countAt

History
histogram.countAt(value): void
Attributes
value:<number>
要查询的值。

返回落在给定值的等效值范围内的 记录值的数量。

M

histogram.diff

History
histogram.diff(other): void
Attributes
此直方图的一个较早快照。

返回一个新的 <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 包含此直方图中没有的值, 例如因为直方图的传入顺序错误。
P

histogram.exceeds

History

由于超过直方图的最高可记录值而未被记录的 值的数量。

P

histogram.exceedsBigInt

History

由于超过直方图的最高可记录值而未被记录的 值的数量。

histogram.export(): void

将直方图序列化为 CBOR 编码的(RFC 8949)Uint8Array, 适用于传输或持久化存储。编码使用桶计数的 增量编码稀疏表示,因此输出大小 随不同记录值的数量而扩展,而不是随桶的总数 扩展。

输出包括所有直方图配置、桶数据和 EWMA 状态(启用时)。可以使用以下方法将其重建为新的直方图: perf_hooks.importHistogram().

CBOR 有效载荷是一个带有整数键的映射:

键类型字段
0uint格式版本(当前为 2)
1uint最低可辨别值
2uint最高可追踪值
3uint有效数字位数
4uint总计数
5uint最小值
6uint最大值
7uint归一化索引偏移
8float64转换比率
9uint计数数组长度
10array增量编码的稀疏计数 [delta, c, ...]
11mapEWMA 状态(禁用时省略)

任何标准的 CBOR 解码器都可以解析该输出。

perf_hooks.importHistogram() 接受 histogram.export() 曾产生的 所有格式版本:

  • 版本 1 由 Node.js v26.9.0 产生。带有版本 1 键或 没有版本键的数据会按原始语义导入:上面未列出的 键会被拒绝。
  • 版本 2 的布局与版本 1 相同。无法识别的键 会被忽略,因此更高版本的 Node.js 可以在不改变版本的情况下 向版本 2 数据添加字段,且数据仍可导入。

具有任何其他版本的数据会被拒绝。

当缺少总计数、最小值或最大值时,会从桶计数中推导出来。 存在的总计数必须与桶计数匹配。

P

histogram.ewmaMean

History

记录值的指数加权移动平均值。仅当 直方图创建时设置了大于 0 的 halfLife 选项时才生效。 当 EWMA 被禁用或没有记录任何值时,返回 0。

P

histogram.ewmaStddev

History

指数加权移动标准差。仅当直方图创建时设置了 大于 0 的 halfLife 选项时才生效。当 EWMA 被禁用或 没有记录任何值时,返回 0。

P

histogram.ewmaErrorRate

History

记录值超过所配置的 threshold 的 EWMA 平滑概率。 仅当直方图创建时同时设置了 halfLife 和 threshold 选项时才生效。未启用或没有记录任何值时 返回 0。

M

histogram.ksTest

History
histogram.ksTest(other): void
Attributes
要比较的直方图。

计算 Kolmogorov-Smirnov 检验统计量,比较此直方图的 分布与 other。值为 0 表示分布相同; 接近 1 的值表示分布完全不相交。通过比较前后直方图, 可用于检测性能回归。

P

histogram.kurtosis

History

记录值的超额峰度。衡量分布尾部相对于 正态分布的厚重程度。正值表示尾部更重 (更极端的离群值);负值表示 尾部更轻。

M

histogram.linearBuckets

History
histogram.linearBuckets(stepSize): void
Attributes
stepSize:<number>
每个线性桶的宽度。

返回重新分桶为等间距区间的直方图数据, 区间大小为 stepSize。可用于可视化和导出。

M

histogram.logBuckets

History
histogram.logBuckets(firstBucket, base): void
Attributes
firstBucket:<number>
第一个桶边界的值。
桶宽度增长的对数底数。必须大于 1。

返回经过重新分桶的直方图数据,各桶采用对数间隔, 其中每个桶的宽度乘以 base。 适用于可视化和导出。

M

histogram.mannWhitneyTest

History
histogram.mannWhitneyTest(other): void
Attributes
要比较的直方图。
uStatistic:<number>
Mann-Whitney U 统计量。
zScore:<number>
z 分数(正态近似)。
pValue:<number>
双尾 p 值。

执行 Mann-Whitney U 检验,比较此直方图是否倾向于 产生比 other 更大或更小的值。与 welchTest() 不同,这是一种 非参数检验,它不对 分布的形状作任何假设。p 值使用带并列校正的 正态近似计算。

P

histogram.max

History

记录到的最大事件循环延迟。

P

histogram.maxBigInt

History

记录到的最大事件循环延迟。

P

histogram.mean

History

记录到的事件循环延迟的平均值。

M

histogram.meanCI

History
histogram.meanCI(options?): void
Attributes
options:<Object>
confidence:<number>
区间的置信水平,介于 0 和 1 之间(不含)。 默认值: 0.95 。
平均值估计,等同于  histogram.mean 。
lower:<number>
置信区间的下限。
upper:<number>
置信区间的上限。

使用 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}]`);
P

histogram.min

History

记录到的最小事件循环延迟。

P

histogram.minBigInt

History

记录到的最小事件循环延迟。

M

histogram.percentile

History
histogram.percentile(percentile): void
Attributes
percentile:<number>
范围 (0, 100] 内的百分位数值。

返回给定百分位数处的值。

M

histogram.percentileBigInt

History
histogram.percentileBigInt(percentile): void
Attributes
percentile:<number>
范围 (0, 100] 内的百分位数值。

返回给定百分位数处的值。

M

histogram.percentileCI

History
histogram.percentileCI(percentile, options?): void
Attributes
percentile:<number>
范围 (0, 100] 内的百分位数值。
options:<Object>
confidence:<number>
区间的置信水平,介于 0 和 1 之间(不含)。 默认值: 0.95 。
value:<number>
点估计(与  histogram.percentile() 相同)。
lower:<number>
置信区间的下限。
upper:<number>
置信区间的上限。

使用精确的二项式方法返回给定百分位数的置信区间。样本 越少,区间越宽,反映出 百分位数估计的不确定性越大。至少需要 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)
P

histogram.percentiles

History

返回一个 Map 对象,详细描述累积的百分位数分布。

P

histogram.percentilesBigInt

History

返回一个 Map 对象,详细描述累积的百分位数分布。

M

histogram.percentilesAt

History
histogram.percentilesAt(percentiles): void
Attributes
percentiles:<number>
[] 范围 (0, 100] 内的百分位数值数组。

返回指定百分位数处的值,通过对直方图数据进行一次 高效遍历计算得出。比多次调用 histogram.percentile() 更高效。

M

histogram.qrde

History
histogram.qrde(options?): void
Attributes
options:<Object>
要返回的等概率密度桶的数量。 必须介于 1 和 1000 之间。不能与  probabilities 同时使用。 默认值: 100 。
probabilities:<number>
[] 自定义概率边界。数组必须 包含 2 到 1001 个严格递增的值,以  0 开头,并以 1 结尾。不能与 bins 同时使用。
dequantize:<string>
控制是否将重复的桶值 确定性地分布在其等值范围内。可以是  'none' 、 'hdr' 或 'all' 。 默认值: 'hdr' 。
cache:<boolean>
为  true 时,保留展开后的直方图快照, 供后续使用 cache: true 的调用复用。当直方图被修改时, 该快照失效。 默认值: false 。
probabilities:<Float64Array>
估计所使用的概率 边界。
quantiles:<Float64Array>
概率边界处的分位数。
densities:<Float64Array>
每个分位数区间内的密度。
count:<bigint>
直方图快照中的值数量。
bucketCount:<number>
已占用的 HDR 桶数量。
corrections:<number>
被钳制到前一个分位数的 非单调浮点结果的数目。
dequantize:<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 峰值
16.3 KiB25 KiB31 KiB
247 KiB188 KiB235 KiB
3352 KiB1.4 MiB1.7 MiB
45.0 MiB20 MiB25 MiB
537 MiB148 MiB185 MiB

最大快照列假设每个可表示的桶都已占用。 较低的 highest 值可减小直方图和临时副本的大小。并发 调用若未命中缓存,则各自需要自己的临时副本和展开的 快照。

HDR 直方图将观测值聚合到等值桶中。 'hdr' 反量化模式将宽度大于一个单位的桶中的 重复值建模为桶分辨率上的连续均匀分布。这 减少了 HDR 量化引入的密度伪影,同时 将重复的单位分辨率值保留为点质量。'all' 模式还会 对重复的单位分辨率值进行反量化。使用 'none' 可 直接使用桶中点计算分组 Harrell-Davis 估计器。

空直方图会返回请求的 probabilities,但产生空的 quantiles 和 densities 数组。未反量化的区间如果其分位数 边界相等,则密度为无穷大。

M

histogram.reset

History
histogram.reset(): void

重置收集到的直方图数据并递增 histogram.resetCount。

P

histogram.resetCount

History

通过 reset() 从该直方图中移除值的次数, 对于 <RecordableHistogram> 则是通过 subtract()。快照保留其 来源在创建时的 resetCount,因此比较两个 快照的 resetCount 可以判断来源在两者之间是否被重置。参见 histogram.diff().

P

histogram.skewness

History

记录值的偏度。衡量分布的 不对称性。正值表示右偏分布 (右侧尾部更长,常见于延迟数据);负值 表示左偏分布。

M

histogram.snapshot

History
histogram.snapshot(): void

返回一个新的、独立的 <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);
P

histogram.stddev

History

记录到的事件循环延迟的标准差。

M

histogram.welchTest

History
histogram.welchTest(other, options?): void
Attributes
要比较的直方图。
options:<Object>
confidence:<number>
区间的置信水平,介于 0 和 1 之间。  默认值: 0.95 。
tStatistic:<number>
Welch t 统计量。
degreesOfFreedom:<number>
Welch-Satterthwaite 自由度。
pValue:<number>
双尾 p 值。
confidenceInterval:<Object>
lower:<number>
均值差异置信区间的 下限。
upper:<number>
上限。

执行 Welch t 检验,比较此直方图与 other 的均值。 p 值表示在原假设(两个分布具有 相同均值)下,观察到至少如此极端的差异的 概率。两个直方图都必须至少有 2 个记录值; 否则结果的 pValue 为 1、tStatistic 为 0。

一个记录事件循环延迟的 Histogram,由 perf_hooks.monitorEventLoopDelay().

M

histogram.disable

History
histogram.disable(): void

禁用事件循环延迟采样。如果采样已 停止则返回 true,如果本就已停止则返回 false。

M

histogram.enable

History
histogram.enable(): void

启用事件循环延迟采样。如果采样已 启动则返回 true,如果本就已启动则返回 false。

M

histogram[Symbol.dispose]

History
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
M

histogram.add

History
histogram.add(other): void
Attributes

将 other 中的值添加到此直方图。

M

histogram.record

History
histogram.record(val): void
Attributes
要记录到直方图中的值。必须是 大于或等于  0 的整数。

小于直方图 lowest 选项的值(包括 0)可能 彼此无法区分。

M

histogram.recordDelta

History
histogram.recordDelta(): void

计算自上次调用 recordDelta() 以来经过的时间 (以纳秒为单位),并将该时长记录到直方图中。

histogram.recordCorrected(val, expectedInterval): void
Attributes
要记录的值。必须是大于或等于  0 的整数。
expectedInterval:<number> | <bigint>
预期的记录间隔。

使用协调遗漏校正记录一个值。当系统停顿 导致无法及时记录时,此方法会在先前记录的值与 val 之间 按 expectedInterval 步长回填中间值。 这弥补了那些原本会低估延迟的 测量间隙。

M

histogram.subtract

History
histogram.subtract(other): void
Attributes

从直方图中减去 other 的值。两个直方图应具有 兼容的配置。会变为负数的桶计数 将被钳制为零。递增 histogram.resetCount。

类:SlidingWindowHistogram

History

将值记录到惰性轮转的直方图块环中。实例通过 perf_hooks.createSlidingWindowHistogram() 创建,不能直接 构造。SlidingWindowHistogram 不继承 <Histogram>; 调用 snapshot() 可将当前窗口具体化为 <Histogram>。

SlidingWindowHistogram 实例无法通过 <MessagePort> 克隆或传输。 <MessagePort>.

M

slidingWindowHistogram.record

History
slidingWindowHistogram.record(val): void
Attributes
要记录的值。必须是大于或等于  0 的整数。

将 val 记录到当前块中。对于基于计数的窗口,每次到达 原生直方图的调用都计入轮转,包括超过 配置的 highest 值的值。

M

slidingWindowHistogram.reset

History
slidingWindowHistogram.reset(): void

使当前窗口中的所有块失效。已分配的块在 重用时惰性重置。

M

slidingWindowHistogram.snapshot

History
slidingWindowHistogram.snapshot(): void

将当前窗口具体化为一个新的、独立的 <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 tails
const { 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');