Node.js v26.11.1 文档


性能测量 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,则从性能时间轴中删除所有 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,则从性能时间表中删除所有 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,则从资源时间轴中移除所有 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])#>

返回一个按时间顺序排列的 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)#>

返回一个按时间顺序排列的 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])#>

  • name <string>
  • options <Object>
    • detail <any> 可随标记附加的可选详细信息。
    • startTime <number> 可选时间戳,用作标记时间。 默认值:performance.now()。

在性能时间线中创建一个新的 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])#>

此属性是 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> 可选。
    • detail <any> 可随度量包含的额外可选细节。
    • duration <number> 开始时间和结束时间之间的持续时间。
    • end <number> | <string> 时间戳,用作结束时间,或用于标识先前记录的标记的字符串。
    • start <number> | <string> 时间戳,用作开始时间,或用于标识先前记录的标记的字符串。
  • 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()#>

返回当前高分辨率毫秒时间戳,其中 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#>

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])#>

这是 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#>

此条目的总经过毫秒数。该值并不适用于所有性能条目类型。

🌐 The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types.

performanceEntry.entryType#>

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

🌐 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#>

性能条目的名称。

🌐 The name of the performance entry.

performanceEntry.startTime#>

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

🌐 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#>

使用 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#>

使用 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#>

entryType 特有的附加细节。

🌐 Additional detail specific to the entryType.

performanceNodeEntry.flags#>

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

当 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_NO
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE

performanceNodeEntry.kind#>

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

当 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_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

垃圾回收('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_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

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> 从 PerformanceEntry startTime 到接收到第一个 DATA 帧之间经过的毫秒数。
  • timeToFirstByteSent <number> PerformanceEntry startTime 与发送第一个 DATA 帧之间经过的毫秒数。
  • timeToFirstHeader <number> PerformanceEntry startTime 与接收第一个头之间经过的毫秒数。

如果 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#>

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#>

Node.js 环境初始化时的高分辨率毫秒时间戳。

🌐 The high resolution millisecond timestamp at which the Node.js environment was initialized.

performanceNodeTiming.idleTime#>

事件循环在其事件提供者(例如 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#>

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#>

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#>

Node.js 进程初始化时的高分辨率毫秒时间戳。

🌐 The high resolution millisecond timestamp at which the Node.js process was initialized.

performanceNodeTiming.uvMetricsInfo#>

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

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

🌐 This is a wrapper to the uv_metrics_info function. It returns the current set of event loop metrics.

这些数值精确到 Number.MAX_SAFE_INTEGER。使用 performanceNodeTiming.uvMetricsInfoBigInt 可以获取 libuv 报告的完整 64 位数值。

🌐 The values are exact up to Number.MAX_SAFE_INTEGER. Use performanceNodeTiming.uvMetricsInfoBigInt to obtain the full 64-bit values reported by libuv.

建议在使用 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.uvMetricsInfoBigInt#>

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

跟 performanceNodeTiming.uvMetricsInfo 一样,只是这些值是 <bigint>,承载 libuv 报告的完整 64 位范围。

🌐 The same as performanceNodeTiming.uvMetricsInfo, except that the values are <bigint>s carrying the full 64-bit range reported by libuv.

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

🌐 Because JSON.stringify() cannot serialize <bigint> values, this property is not enumerable and is not included in the output of performanceNodeTiming.toJSON(). Copies of performance.nodeTiming made by spreading its enumerable properties, for example, remain serializable.

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

setImmediate(() => {
  console.log(performance.nodeTiming.uvMetricsInfoBigInt);
});import { performance } from 'node:perf_hooks';

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

performanceNodeTiming.v8Start#>

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#>

在调度 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#>

表示启动重定向的抓取开始时间的高分辨率毫秒时间戳。

🌐 The high resolution millisecond timestamp that represents the start time of the fetch which initiates the redirect.

performanceResourceTiming.redirectEnd#>

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

🌐 The high resolution millisecond timestamp that will be created immediately after receiving the last byte of the response of the last redirect.

performanceResourceTiming.fetchStart#>

在 Node.js 开始获取资源之前的高分辨率毫秒时间戳。

🌐 The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource.

performanceResourceTiming.domainLookupStart#>

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

🌐 The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup for the resource.

performanceResourceTiming.domainLookupEnd#>

高分辨率毫秒时间戳,表示 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#>

高分辨率毫秒时间戳,表示 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#>

高精度毫秒时间戳,表示 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#>

高分辨率毫秒时间戳,表示 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#>

高精度毫秒时间戳,表示 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.finalResponseHeadersStart#>

高分辨率毫秒时间戳,表示在 Node.js 接收到最终响应的第一个字节后立即的时间,而不是暂时响应的时间。

🌐 The high resolution millisecond timestamp representing the time immediately after Node.js receives the first byte of the final response, as opposed to an interim response.

performanceResourceTiming.firstInterimResponseStart#>

高分辨率毫秒时间戳,表示在 Node.js 接收到第一个过渡响应的第一个字节之后的时间,比如 103 Early Hints 响应。

🌐 The high resolution millisecond timestamp representing the time immediately after Node.js receives the first byte of the first interim response, such as a 103 Early Hints response.

performanceResourceTiming.responseStart#>

表示 Node.js 收到服务器响应的第一个字节后立即时间的高分辨率毫秒时间戳。当它非零时是 firstInterimResponseStart,否则是 finalResponseHeadersStart。

🌐 The high resolution millisecond timestamp representing the time immediately after Node.js receives the first byte of the response from the server. This is firstInterimResponseStart when it is non-zero, and finalResponseHeadersStart otherwise.

performanceResourceTiming.responseEnd#>

高精度毫秒时间戳,表示在 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#>

表示获取的资源大小(以字节为单位)的数字。大小包括响应头字段以及响应负载主体。

🌐 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#>

表示从 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#>

表示从 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.renderBlockingStatus#>

资源的渲染阻塞状态。它要么是 'blocking',要么是 'non-blocking'。

🌐 The render blocking status of the resource. It is either 'blocking' or 'non-blocking'.

performanceResourceTiming.contentType#>

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

🌐 The minimized MIME type of the content of the fetched resource, or an empty string if it cannot be determined.

performanceResourceTiming.contentEncoding#>

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

🌐 The content encoding of the fetched resource, such as 'gzip' or 'br'.

performanceResourceTiming.toJSON()#>

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

🌐 Returns a object that is the JSON representation of the PerformanceResourceTiming object

类:PerformanceObserver#>

🌐 Class: PerformanceObserver

PerformanceObserver.supportedEntryTypes#>

获取支持的类型。

🌐 Get supported types.

new PerformanceObserver(callback)#>

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()#>

类: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])#>

返回一个按时间顺序排列的 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)#>

返回一个按时间顺序排列的 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.createSlidingWindowHistogram(options)#>

  • 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 中的一个。
    • lowest <number> | <bigint> 最低可识别的值。必须是大于 0 的整数值。默认值: 1。
    • highest <number> | <bigint> 可记录的最高值。必须是一个整数,并且大于或等于 lowest 的两倍。默认值: Number.MAX_SAFE_INTEGER。
    • figures <number> 精确度的位数。必须是 1 到 5 之间的整数。默认值: 3。
  • 返回:SlidingWindowHistogram

创建一个 SlidingWindowHistogram,它保留最新的 chunks 直方图块。旋转是懒惰的,不会创建计时器。基于时间的旋转在调用 record() 或 snapshot() 时评估。基于数量的旋转在调用 record() 时评估。

🌐 Creates a SlidingWindowHistogram that retains the latest chunks histogram chunks. Rotation is lazy and does not create a timer. Time-based rotation is evaluated when record() or snapshot() is called. Count-based rotation is evaluated when record() is called.

在构建过程中会分配一个直方图块。额外的块会按需分配。窗口使用的最大本地内存会随着 chunks 以及 lowest、highest 和 figures 直方图选项而变化。

🌐 One histogram chunk is allocated during construction. Additional chunks are allocated lazily. The maximum native memory used by the window scales with chunks and with the lowest, highest, and figures histogram options.

窗口边界具有块级精度。对于持续时间为 D 的 N 个块,记录的值会保留在 (N - 1) * D 到 N * D 毫秒之间。一旦基于计数的窗口被填充,它会保留 (N - 1) * C + 1 到 N * C 次记录尝试,其中 C 是 recordsPerChunk。超过 highest 的记录尝试会在确定基于计数的轮换时被考虑进去。

🌐 The window boundary has chunk-level precision. With N chunks of duration D, a recorded value is retained for between (N - 1) * D and N * D milliseconds. Once a count-based window is populated, it retains between (N - 1) * C + 1 and N * C recording attempts, where C is recordsPerChunk. Recording attempts which exceed highest are included when determining count-based rotation.

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

const window = createSlidingWindowHistogram({
  chunks: 6,
  chunkDuration: 10_000,
});

window.record(20_000_000);

// Materialize the current window as an independent Histogram.
const snapshot = window.snapshot();
console.log(snapshot.percentile(99)); 

perf_hooks.importHistogram(data)#>

从 CBOR 编码的 Uint8Array 重建直方图。返回的直方图是一个完整的 <RecordableHistogram>,包含所有桶数据、配置和 EWMA 状态。可以向其中记录新值。

🌐 Reconstructs a histogram from a CBOR-encoded Uint8Array. The returned histogram is a full <RecordableHistogram> with all bucket data, configuration, and EWMA state restored. New values can be recorded into it.

histogram.export() 生成的任何格式版本的数据都可以导入。详情请参见 直方图导出格式兼容性。

🌐 Data in any format version produced by histogram.export() can be imported. See histogram export format compatibility for details.

const { createHistogram, importHistogram } = require('node:perf_hooks');

const h = createHistogram();
for (let i = 1; i <= 1000; i++) h.record(i);

// Serialize and reconstruct
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]])#>

  • 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>
    • samplePerIteration <boolean> 当 true 时,每次事件循环迭代都会采样一次。默认值: false。
    • resolution <number> 用于基于间隔采样的采样率(毫秒)。必须大于零。当 samplePerIteration 为 true 时,此选项将被忽略。默认值: 10。
    • lowest <number> | <bigint> 可察觉的最小延迟,单位为纳秒。必须是大于 0 的整数值。默认值: 当 samplePerIteration 为 true 时为 1,否则为 1000。
    • highest <number> | <bigint> 可记录的最高延迟,单位为纳秒。必须是一个整数,且大于或等于 lowest 的两倍。默认值: 2n ** 63n - 1n。
    • figures <number> 精确位数。必须是介于 1 和 5 之间的整数。默认值: 3。
  • 返回: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.

lowest、highest 和 figures 选项的配置方式和 perf_hooks.createHistogram() 一样。lowest 必须大于 0,因为事件循环延迟为零是不可能的:事件循环有最小开销,而且测量本身依赖于事件循环的运行。大于 highest 的延迟不会被记录,而是由 histogram.exceeds 来计数。使用基于间隔的采样时,每个样本都包含 resolution,所以 highest 应该比 resolution * 1e6 高很多。直方图的内存使用取决于这些选项,而不是样本数量。

🌐 The lowest, highest, and figures options configure the histogram as they do for perf_hooks.createHistogram(). lowest must be greater than 0 because an event loop delay of zero is not possible: the event loop has a minimal overhead, and the measurement itself depends on the event loop turning. Delays greater than highest are not recorded, and are counted by histogram.exceeds instead. With interval-based sampling, every sample includes the resolution, so highest should be well above resolution * 1e6. The histogram's memory use depends on these options, not on the number of samples.

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])#>

此属性是 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.burnRate(sloTarget)#>

  • sloTarget <number> SLO 目标是一个介于 0 和 1 之间的分数(不包括 0 和 1)。例如,99.9% 的 SLO 可以写成 0.999。
  • 返回:<number>

返回 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.count#>

直方图记录的样本数。

🌐 The number of samples recorded by the histogram.

histogram.countBigInt#>

直方图记录的样本数。

🌐 The number of samples recorded by the histogram.

histogram.ccdf(value)#>

  • value <number> 要查询的值。
  • 返回:<number> 一个介于 0.0 和 1.0 之间的概率。

返回给定值的互补累积分布函数(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)#>

  • value <number> 要查询的值。
  • 返回:<number> 一个介于 0.0 和 1.0 之间的概率。

返回给定值的累积分布函数(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)#>

计算 科恩的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.diff(other)#>

返回一个新的 <Histogram>,其中包含在采集 other 后此直方图记录的值。两个直方图都不会被更改。要在不调用 reset() 的情况下获取每个时间间隔记录的值,可以通过计算每个快照的差值,并将该快照作为下一个时间间隔的基线:

🌐 Returns a new <Histogram> containing the values recorded in this histogram after other was taken. Neither histogram is changed. To get the values recorded during each interval without calling reset(), compute each difference from a snapshot and keep that snapshot as the baseline for the next interval:

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

const histogram = monitorEventLoopDelay();
histogram.enable();
let previous = histogram.snapshot();

setInterval(() => {
  const current = histogram.snapshot();
  // After a reset, use everything recorded since the reset.
  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。

🌐 The count, exceeds, and bucket counts of the returned histogram are the differences between the two histograms. Its min and max are computed from the buckets of the difference, it has no EWMA state, and its resetCount is 0.

这个方法会抛出:

🌐 This method throws:

  • ERR_INVALID_ARG_VALUE 如果 other 有不同的 lowest、highest 或 figures 配置。
  • ERR_INVALID_STATE 如果自从 other 以来,从这个直方图中删除了某些值,当两个直方图的 resetCount 不同时,就会出现这种情况。
  • ERR_INVALID_ARG_VALUE 如果 other 包含不在此直方图中的值,例如因为直方图的传入顺序错误。

histogram.exceeds#>

因为超过了直方图的最高可记录值而未被记录的数值数量。

🌐 The number of values that were not recorded because they exceeded the histogram's highest recordable value.

histogram.exceedsBigInt#>

因为超过了直方图的最高可记录值而未被记录的数值数量。

🌐 The number of values that were not recorded because they exceeded the histogram's highest recordable value.

histogram.export()#>

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

🌐 Serializes the histogram to a CBOR-encoded (RFC 8949) Uint8Array suitable for transmission or persistent storage. The encoding uses a delta-encoded sparse representation of the bucket counts, so the output size scales with the number of distinct recorded values rather than the total bucket count.

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

🌐 The output includes all histogram configuration, bucket data, and EWMA state (when enabled). It can be reconstructed into a new histogram using perf_hooks.importHistogram().

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

🌐 The CBOR payload is a map with integer keys:

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

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

🌐 Any standard CBOR decoder can parse the output.

直方图导出格式兼容性#>

🌐 Histogram export format compatibility

perf_hooks.importHistogram() 接受 histogram.export() 生成的每个格式版本:

  • 版本 1 是由 Node.js v26.9.0 生成的。带有版本 1 键的数据,或者没有版本键的数据,将按原始语义导入:上述未列出的键会被拒绝。
  • 版本2的布局和版本1一样。不被识别的键会被忽略,所以Node.js的后续版本可以向版本2的数据添加字段而不改变版本号,而且数据仍然可以导入。

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

🌐 Data with any other version is rejected.

当总数、最小值或最大值缺失时,它会根据桶计数来推算。已有的总数必须与桶计数相匹配。

🌐 When the total count, min, or max value is absent, it is derived from the bucket counts. A total count that is present must match the bucket counts.

histogram.ewmaMean#>

记录值的指数加权移动平均。只有当直方图使用大于 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#>

指数加权移动标准差。只有在使用大于 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#>

记录值超过配置的 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.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#>

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

🌐 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 <number> 每个线性桶的宽度。
  • 返回:<Map> 一个显示桶边界值对应数量的地图。

返回重新分桶到线性间隔为 stepSize 的直方图数据。适合可视化和导出。

🌐 Returns the histogram data rebucketed into linearly-spaced intervals of stepSize. Useful for visualization and export.

histogram.logBuckets(firstBucket, base)#>

  • firstBucket <number> 第一个桶边界的值。
  • base <number> 桶宽增长的对数底数。必须大于 1。
  • 返回:<Map> 一个显示桶边界值对应数量的地图。

返回按对数间隔重新分桶的直方图数据,每个桶的宽度乘以 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)#>

执行 曼-惠特尼 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#>

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

🌐 The maximum recorded event loop delay.

histogram.maxBigInt#>

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

🌐 The maximum recorded event loop delay.

histogram.mean#>

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

🌐 The mean of the recorded event loop delays.

histogram.meanCI([options])#>

  • options <Object>
    • confidence <number> 区间的置信水平,在 0 和 1 之间(不包括0和1)。默认值:0.95。
  • 返回:<Object>
    • mean <number> 平均估计,相当于 histogram.mean。
    • lower <number> 置信区间的下界
    • upper <number> 置信区间的上限。

使用Student的t分布和样本标准误差返回均值的双侧置信区间。较高的置信水平会产生更宽的区间。该区间假设样本是独立且近似正态分布的,尽管对于足够大的样本,这种近似是稳健的。

🌐 Returns a two-sided confidence interval for the mean using Student's t-distribution and the sample standard error. A higher confidence level produces a wider interval. This interval assumes that samples are independent and approximately normally distributed, although the approximation is robust for sufficiently large samples.

结果反映了直方图配置的精度,并且是根据其桶所表示的值计算得出的。当记录的值少于两个时,lower 和 upper 为 NaN。当所有记录的值相等时,lower 和 upper 等于 mean。

🌐 The result reflects the histogram's configured precision and is calculated from the values represented by its buckets. With fewer than two recorded values, lower and upper are NaN. When all recorded values are equal, lower and upper equal 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}]`); 

histogram.min#>

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

🌐 The minimum recorded event loop delay.

histogram.minBigInt#>

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

🌐 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>
    • value <number> 点估计(同 histogram.percentile())。
    • lower <number> 置信区间的下界
    • upper <number> 置信区间的上限。

使用精确二项式方法返回给定百分位数的置信区间。样本越少,区间越宽,反映出百分位数估计的不确定性越大。至少需要记录 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 对象,详细说明累计百分比分布。

🌐 Returns a Map object detailing the accumulated percentile distribution.

histogram.percentilesBigInt#>

返回一个 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.qrde([options])#>

  • options <Object>
    • bins <number> 要返回的等概率密度区间数量。必须在 1 到 1000 之间。不能与 probabilities 一起使用。默认值: 100。
    • probabilities <number[]> 自定义概率边界。数组必须包含 2 到 1001 个严格递增的值,以 0 开始,以 1 结束。不能与 bins 一起使用。
    • dequantize <string> 控制重复的桶值是否在它们的等值范围内以确定性的方式分布。可以是 'none'、'hdr' 或 'all'。默认值: 'hdr'。
    • cache <boolean> 当 true 时,会保留扩展的直方图快照以供后续使用 cache: true 调用。当直方图被修改时,该快照会失效。默认值: false。
  • 返回:<Promise> 填充有一个包含以下内容的<Object>:
    • 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 权重使用二阶渐近近似,以避免在大样本数下出现数值收敛损失。

🌐 Returns a quantile-respectful density estimate based on the Harrell-Davis quantile estimator. By default, bins generates equal probability boundaries. The probabilities option can instead focus the estimate on regions such as p90, p99, p99.9, and p99.99. The density for interval i contains probability mass probabilities[i + 1] - probabilities[i]. The histogram is snapshotted when the method is called. Snapshot expansion and the estimate are calculated in the libuv thread pool. Highly concentrated beta weights use a second-order asymptotic approximation to avoid numerical convergence loss at large sample counts.

将 cache 设置为 true 可以避免在未改变的直方图上多次请求估算时重复捕获和展开快照。保留的快照占用的内存与已使用的 HDR 桶数量成正比,并且在下次修改直方图时会被释放。

🌐 Setting cache to true avoids repeating snapshot capture and expansion when several estimates are requested from an unchanged histogram. The retained snapshot uses memory proportional to the number of occupied HDR buckets and is released when the histogram is next modified.

QRDE 临时大约使用额外一个 HDR 计数数组,加上每个占用桶 32 字节。使用 cache: true 时,每个桶扩展的 32 字节快照仍然保持分配。以下估算使用 lowest: 1 和 highest: Number.MAX_SAFE_INTEGER,不包含分配器和 JavaScript 对象的开销:

🌐 QRDE temporarily uses approximately one additional HDR count array plus 32 bytes per occupied bucket. With cache: true, the expanded 32-byte-per-bucket snapshot remains allocated. The following estimates use lowest: 1 and highest: Number.MAX_SAFE_INTEGER and exclude allocator and JavaScript object overhead:

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 值会减小直方图和临时副本的大小。每次并发调用如果没有命中缓存,都需要自己的临时副本和扩展的快照。

🌐 The maximum snapshot column assumes every representable bucket is occupied. Lower highest values reduce histogram and temporary copy sizes. Concurrent calls that miss the cache each require their own temporary copy and expanded snapshot.

HDR 直方图将观察值汇总到等值的桶中。'hdr' 反量化模式将宽于一个单位的桶中的重复值建模为在桶分辨率上的连续均匀分布。这可以在保留单位分辨率重复值作为点质量的同时,减少 HDR 量化引入的密度伪影。'all' 模式也会反量化单位分辨率的重复值。使用 'none' 可以直接使用桶的中点来计算分组的 Harrell-Davis 估计量。

🌐 HDR histograms aggregate observations into equivalent-value buckets. The 'hdr' dequantization mode models repeated values in buckets wider than one unit as a continuous uniform distribution over the bucket resolution. This reduces density artifacts introduced by HDR quantization while preserving repeated unit-resolution values as point masses. The 'all' mode also dequantizes repeated unit-resolution values. Use 'none' to calculate the grouped Harrell-Davis estimator using bucket midpoints directly.

一个空的直方图会返回请求的 probabilities,但会生成空的 quantiles 和 densities 数组。一个非去量化的区间,如果其分位数边界相等,会有无限的密度。

🌐 An empty histogram returns the requested probabilities but produces empty quantiles and densities arrays. A non-dequantized interval whose quantile boundaries are equal has an infinite density.

histogram.reset()#>

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

🌐 Resets the collected histogram data and increments histogram.resetCount.

histogram.resetCount#>

从这个直方图中移除数值的次数由 reset() 或者,对于 <RecordableHistogram>,由 subtract()。快照在被拍摄时拥有其源的 resetCount,所以比较两个快照的 resetCount 可以显示它们之间源是否被重置。参见 histogram.diff()。

🌐 The number of times values have been removed from this histogram by reset() or, for a <RecordableHistogram>, subtract(). A snapshot has the resetCount of its source at the time it was taken, so comparing the resetCount of two snapshots shows whether the source was reset between them. See histogram.diff().

histogram.skewness#>

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

🌐 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.snapshot()#>

返回一个新的、独立的 <Histogram>,其中包含此直方图当前状态的副本:它的配置、记录的值、exceeds 计数以及 EWMA 状态。在此方法返回后记录到此直方图的值,以及之后对 reset() 的调用,都不会改变返回的直方图。这提供了一个在仍在记录的直方图(例如已启用的 ELDHistogram)上的稳定视图。

🌐 Returns a new, independent <Histogram> containing a copy of this histogram's current state: its configuration, recorded values, exceeds count, and EWMA state. Values recorded into this histogram after this method returns, and later calls to reset(), do not change the returned histogram. This provides a stable view of a histogram that is still recording, such as an enabled ELDHistogram.

值无法记录到返回的直方图中。拍摄快照会复制每个桶,因此其时间和内存开销取决于直方图的 lowest、highest 和 figures 配置,而不是取决于已记录值的数量。

🌐 Values cannot be recorded into the returned histogram. Taking a snapshot copies every bucket, so both its time and memory cost depend on the histogram's lowest, highest, and figures configuration rather than on the number of recorded values.

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

const histogram = monitorEventLoopDelay();
histogram.enable();

setTimeout(() => {
  const snapshot = histogram.snapshot();
  console.log(snapshot.percentile(99));
  histogram.disable();
}, 1000); 

histogram.stddev#>

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

🌐 The standard deviation of the recorded event loop delays.

histogram.welchTest(other[, options])#>

执行 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()#>

禁用事件循环延迟采样。如果采样被停止,返回 true;如果采样已经停止,返回 false。

🌐 Disables event loop delay sampling. Returns true if sampling was stopped, false if it was already stopped.

histogram.enable()#>

启用事件循环延迟采样。如果采样已启动,则返回 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 中的值添加到此直方图中。

🌐 Adds the values from other to this histogram.

histogram.record(val)#>

  • val <number> | <bigint> 要在直方图中记录的数量。必须是大于或等于 0 的整数。

比直方图的 lowest 选项小的值,包括 0,可能彼此之间无法区分。

🌐 Values smaller than the histogram's lowest option, including 0, might not be distinguishable from each other.

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 的值。两个直方图的配置应该兼容。变为负数的桶计数会被限制为零。增加 histogram.resetCount。

🌐 Subtracts the values of other from this histogram. Both histograms should have compatible configurations. Bucket counts that would become negative are clamped to zero. Increments histogram.resetCount.

类:SlidingWindowHistogram#>

🌐 Class: SlidingWindowHistogram

将值记录到一个懒惰旋转的直方图块环中。实例是使用 perf_hooks.createSlidingWindowHistogram() 创建的,不能直接构造。SlidingWindowHistogram 并不扩展 <Histogram>;调用 snapshot() 将当前窗口具体化为 <Histogram>。

🌐 Records values into a lazily rotated ring of histogram chunks. Instances are created using perf_hooks.createSlidingWindowHistogram() and cannot be constructed directly. A SlidingWindowHistogram does not extend <Histogram>; call snapshot() to materialize the current window as a <Histogram>.

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

slidingWindowHistogram.record(val)#>

  • val <number> | <bigint> 要记录的金额。必须是大于或等于 0 的整数。

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

🌐 Records val in the current chunk. For a count-based window, every call that reaches the native histogram counts toward rotation, including values which exceed the configured highest value.

slidingWindowHistogram.reset()#>

使当前窗口中的所有块无效。分配的块在重新使用时会被懒惰地重置。

🌐 Invalidates all chunks in the current window. Allocated chunks are reset lazily when reused.

slidingWindowHistogram.snapshot()#>

将当前窗口物化为新的独立 <Histogram>。本方法返回后记录或过期的值不会改变返回的直方图。物化会分配一个直方图并合并每个保留的块。

🌐 Materializes the current window as a new, independent <Histogram>. Values recorded or expired after this method returns do not change the returned histogram. Materialization allocates one histogram and merges every retained chunk.

直方图分析示例#>

🌐 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');
Node.js 中文网 - 粤ICP备13048890号