- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v22.22.0 文档
- Node.js v22.22.0
-
目录
- 性能测量 API
perf_hooks.performanceperformance.clearMarks([name])performance.clearMeasures([name])performance.clearResourceTimings([name])performance.eventLoopUtilization([utilization1[, utilization2]])performance.getEntries()performance.getEntriesByName(name[, type])performance.getEntriesByType(type)performance.mark(name[, options])performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])performance.measure(name[, startMarkOrOptions[, endMark]])performance.nodeTimingperformance.now()performance.setResourceTimingBufferSize(maxSize)performance.timeOriginperformance.timerify(fn[, options])performance.toJSON()
- 类:
PerformanceEntry - 类:
PerformanceMark - 类:
PerformanceMeasure - 类:
PerformanceNodeEntry - 类:
PerformanceNodeTiming - 类:
PerformanceResourceTimingperformanceResourceTiming.workerStartperformanceResourceTiming.redirectStartperformanceResourceTiming.redirectEndperformanceResourceTiming.fetchStartperformanceResourceTiming.domainLookupStartperformanceResourceTiming.domainLookupEndperformanceResourceTiming.connectStartperformanceResourceTiming.connectEndperformanceResourceTiming.secureConnectionStartperformanceResourceTiming.requestStartperformanceResourceTiming.responseEndperformanceResourceTiming.transferSizeperformanceResourceTiming.encodedBodySizeperformanceResourceTiming.decodedBodySizeperformanceResourceTiming.toJSON()
- 类:
PerformanceObserver - 类:
PerformanceObserverEntryList perf_hooks.createHistogram([options])perf_hooks.monitorEventLoopDelay([options])- 类:
Histogramhistogram.counthistogram.countBigInthistogram.exceedshistogram.exceedsBigInthistogram.maxhistogram.maxBigInthistogram.meanhistogram.minhistogram.minBigInthistogram.percentile(percentile)histogram.percentileBigInt(percentile)histogram.percentileshistogram.percentilesBigInthistogram.reset()histogram.stddev
- 类:
IntervalHistogram 继承自 Histogram - 类:
RecordableHistogram 继承自 Histogram - 示例
- 性能测量 API
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- env 环境变量
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
性能测量 API#>
【Performance measurement APIs】
源代码: lib/perf_hooks.js
该模块提供了 W3C 网页性能接口 子集的实现,以及用于 Node.js 特定性能测量的额外 API。
【This module provides an implementation of a subset of the W3C Web Performance APIs as well as additional APIs for Node.js-specific performance measurements.】
Node.js 支持以下 网页性能接口:
【Node.js supports the following Web Performance APIs:】
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
performance.clearMarks();
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');
performance.mark('A');
doSomeLongRunningProcess(() => {
performance.measure('A to Now', 'A');
performance.mark('B');
performance.measure('A to B', 'A', 'B');
});const { PerformanceObserver, performance } = require('node:perf_hooks');
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');
performance.mark('A');
(async function doSomeLongRunningProcess() {
await new Promise((r) => setTimeout(r, 5000));
performance.measure('A to Now', 'A');
performance.mark('B');
performance.measure('A to B', 'A', 'B');
})();
perf_hooks.performance#>
一个可以用于收集当前 Node.js 实例性能指标的对象。它类似于浏览器中的 window.performance。
【An object that can be used to collect performance metrics from the current
Node.js instance. It is similar to window.performance in browsers.】
performance.clearMarks([name])#>
name<string>
如果未提供 name,则从性能时间轴中删除所有 PerformanceMark 对象。如果提供了 name,则仅删除指定名称的标记。
【If name is not provided, removes all PerformanceMark objects from the
Performance Timeline. If name is provided, removes only the named mark.】
performance.clearMeasures([name])#>
name<string>
如果未提供 name,则从性能时间表中删除所有 PerformanceMeasure 对象。如果提供了 name,则仅删除指定名称的测量。
【If name is not provided, removes all PerformanceMeasure objects from the
Performance Timeline. If name is provided, removes only the named measure.】
performance.clearResourceTimings([name])#>
name<string>
如果未提供 name,则从资源时间轴中移除所有 PerformanceResourceTiming 对象。如果提供了 name,则仅移除指定名称的资源。
【If name is not provided, removes all PerformanceResourceTiming objects from
the Resource Timeline. If name is provided, removes only the named resource.】
performance.eventLoopUtilization([utilization1[, utilization2]])#>
utilization1<Object> 先前调用eventLoopUtilization()的结果。utilization2<Object> 在utilization1之前调用eventLoopUtilization()的结果。- 返回值: <Object>
eventLoopUtilization() 方法返回一个对象,该对象包含事件循环在空闲和活动状态下的累计时间,以高精度毫秒计时器表示。utilization 值是计算得到的事件循环利用率(ELU)。
【The eventLoopUtilization() method 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);
});'use strict';
const { eventLoopUtilization } = require('node:perf_hooks').performance;
const { spawnSync } = require('node:child_process');
setImmediate(() => {
const elu = eventLoopUtilization();
spawnSync('sleep', ['5']);
console.log(eventLoopUtilization(elu).utilization);
});
虽然在运行此脚本时 CPU 大部分处于空闲状态,但 utilization 的值是 1。这是因为对 child_process.spawnSync() 的调用阻塞了事件循环的进行。
【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.】
performance.getEntries()#>
返回按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。如果你只对某些类型或具有特定名称的性能条目感兴趣,请参阅 performance.getEntriesByType() 和 performance.getEntriesByName()。
【Returns a list of PerformanceEntry objects in chronological order with
respect to performanceEntry.startTime. If you are only interested in
performance entries of certain types or that have certain names, see
performance.getEntriesByType() and performance.getEntriesByName().】
performance.getEntriesByName(name[, type])#>
name<string>type<string>- 返回值: <PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.name 等于 name,并且可选地,performanceEntry.entryType 等于 type。
【Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.name is
equal to name, and optionally, whose performanceEntry.entryType is equal to
type.】
performance.getEntriesByType(type)#>
type<string>- 返回: <PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,顺序基于 performanceEntry.startTime,且这些对象的 performanceEntry.entryType 等于 type。
【Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.entryType
is equal to type.】
performance.mark(name[, options])#>
在性能时间线中创建一个新的 PerformanceMark 条目。PerformanceMark 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'mark',且 performanceEntry.duration 始终为 0。性能标记用于标记性能时间线中的特定重要时刻。
【Creates a new PerformanceMark entry in the Performance Timeline. A
PerformanceMark is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'mark', and whose
performanceEntry.duration is always 0. Performance marks are used
to mark specific significant moments in the Performance Timeline.】
创建的 PerformanceMark 条目会被放入全局性能时间线中,并且可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当执行观察时,应使用 performance.clearMarks 手动将条目从全局性能时间线中清除。
【The created PerformanceMark entry is put in the global Performance Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with performance.clearMarks.】
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])#>
timingInfo<Object> 获取时间信息requestedUrl<string> 资源 URLinitiatorType<string> 发起者名称,例如:'fetch'global<Object>cacheMode<string> 缓存模式必须是空字符串 ('') 或 'local'bodyInfo<Object> 获取响应主体信息responseStatus<number> 响应的状态码deliveryType<string> 传递类型。 默认值:''。
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
【This property is an extension by Node.js. It is not available in Web browsers.】
在资源时间线中创建一个新的 PerformanceResourceTiming 条目。PerformanceResourceTiming 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'resource'。性能资源用于标记资源时间线中的某些时刻。
【Creates a new PerformanceResourceTiming entry in the Resource Timeline. A
PerformanceResourceTiming is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'resource'. Performance resources
are used to mark moments in the Resource Timeline.】
创建的 PerformanceMark 条目会被放入全局资源时间线中,并且可以使用 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 查询。当执行观察时,应使用 performance.clearResourceTimings 手动从全局性能时间线中清除这些条目。
【The created PerformanceMark entry is put in the global Resource Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with performance.clearResourceTimings.】
performance.measure(name[, startMarkOrOptions[, endMark]])#>
name<string>startMarkOrOptions<string> | <Object> 可选。endMark<string> 可选。如果startMarkOrOptions是一个 <Object>,则必须省略。
在性能时间轴中创建一个新的 PerformanceMeasure 条目。PerformanceMeasure 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'measure',而其 performanceEntry.duration 用于测量从 startMark 到 endMark 经过的毫秒数。
【Creates a new PerformanceMeasure entry in the Performance Timeline. A
PerformanceMeasure is a subclass of PerformanceEntry whose
performanceEntry.entryType is always 'measure', and whose
performanceEntry.duration measures the number of milliseconds elapsed since
startMark and endMark.】
startMark 参数可以识别性能时间线中任何 已存在的 PerformanceMark,也可以识别 PerformanceNodeTiming 类提供的任何时间戳属性。如果指定的 startMark 不存在,则会抛出错误。
【The startMark argument may identify any existing PerformanceMark in the
Performance Timeline, or may identify any of the timestamp properties
provided by the PerformanceNodeTiming class. If the named startMark does
not exist, an error is thrown.】
可选的 endMark 参数必须标识性能时间线中任何 已存在 的 PerformanceMark,或 PerformanceNodeTiming 类提供的任何时间戳属性。如果未传递该参数,endMark 将为 performance.now();否则,如果指定的 endMark 不存在,将抛出错误。
【The optional endMark argument must identify any existing PerformanceMark
in the Performance Timeline or any of the timestamp properties provided by the
PerformanceNodeTiming class. endMark will be performance.now()
if no parameter is passed, otherwise if the named endMark does not exist, an
error will be thrown.】
创建的 PerformanceMeasure 条目会被放入全局性能时间线中,并且可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当执行观察时,应使用 performance.clearMeasures 手动清除全局性能时间线中的条目。
【The created PerformanceMeasure entry is put in the global Performance Timeline
and can be queried with performance.getEntries,
performance.getEntriesByName, and performance.getEntriesByType. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with performance.clearMeasures.】
performance.nodeTiming#>
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
【This property is an extension by Node.js. It is not available in Web browsers.】
PerformanceNodeTiming 类的一个实例,它提供特定 Node.js 操作里程碑的性能指标。
【An instance of the PerformanceNodeTiming class that provides performance
metrics for specific Node.js operational milestones.】
performance.now()#>
- 返回: <number>
返回当前高分辨率毫秒时间戳,其中 0 表示当前 node 进程的起始时间。
【Returns the current high resolution millisecond timestamp, where 0 represents
the start of the current node process.】
performance.setResourceTimingBufferSize(maxSize)#>
将全局性能资源计时缓冲区大小设置为指定数量的“resource”类型性能条目对象。
【Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects.】
默认情况下,最大缓冲区大小设置为 250。
【By default the max buffer size is set to 250.】
performance.timeOrigin#>
- 类型: <number>
timeOrigin 指定了当前 node 进程开始的高分辨率毫秒时间戳,以 Unix 时间为单位测量。
【The timeOrigin specifies the high resolution millisecond timestamp at
which the current node process began, measured in Unix time.】
performance.timerify(fn[, options])#>
fn<Function>options<Object>histogram<RecordableHistogram> 使用perf_hooks.createHistogram()创建的直方图对象,用于记录以纳秒为单位的运行时持续时间。
此属性是 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 { performance, PerformanceObserver } from 'node:perf_hooks';
function someFunction() {
console.log('hello world');
}
const wrapped = performance.timerify(someFunction);
const obs = new PerformanceObserver((list) => {
console.log(list.getEntries()[0].duration);
performance.clearMarks();
performance.clearMeasures();
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
// A performance timeline entry will be created
wrapped();const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
function someFunction() {
console.log('hello world');
}
const wrapped = performance.timerify(someFunction);
const obs = new PerformanceObserver((list) => {
console.log(list.getEntries()[0].duration);
performance.clearMarks();
performance.clearMeasures();
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
// A performance timeline entry will be created
wrapped();
如果被封装的函数返回一个 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.】
performance.toJSON()#>
一个对象,它是 performance 对象的 JSON 表示形式。它类似于浏览器中的 window.performance.toJSON。
【An object which is JSON representation of the performance object. It
is similar to window.performance.toJSON in browsers.】
事件:'resourcetimingbufferfull'#>
【Event: 'resourcetimingbufferfull'】
当全局性能资源时序缓冲区已满时,会触发 'resourcetimingbufferfull' 事件。在事件监听器中,可以使用 performance.setResourceTimingBufferSize() 调整资源时序缓冲区大小,或者使用 performance.clearResourceTimings() 清空缓冲区,以便向性能时间线缓冲区添加更多条目。
【The 'resourcetimingbufferfull' event is fired when the global performance
resource timing buffer is full. Adjust resource timing buffer size with
performance.setResourceTimingBufferSize() or clear the buffer with
performance.clearResourceTimings() in the event listener to allow
more entries to be added to the performance timeline buffer.】
类:PerformanceEntry#>
【Class: PerformanceEntry】
此类的构造函数不直接暴露给用户。
【The constructor of this class is not exposed to users directly.】
performanceEntry.duration#>
- 类型: <number>
此条目的总经过毫秒数。该值并不适用于所有性能条目类型。
【The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types.】
performanceEntry.entryType#>
- 类型: <string>
性能条目的类型。它可以是以下之一:
【The type of the performance entry. It may be one of:】
'dns'(仅限 Node.js)'function'(仅限 Node.js)'gc'(仅限 Node.js)'http2'(仅限 Node.js)'http'(仅限 Node.js)'mark'(可在 Web 上使用)'measure'(可在 Web 上使用)'net'(仅限 Node.js)'node'(仅限 Node.js)'resource'(可在 Web 上使用)
performanceEntry.name#>
- 类型: <string>
性能条目的名称。
【The name of the performance entry.】
performanceEntry.startTime#>
- 类型: <number>
标记性能条目开始时间的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp marking the starting time of the Performance Entry.】
类:PerformanceMark#>
【Class: PerformanceMark】
显示通过 Performance.mark() 方法创建的标记。
【Exposes marks created via the Performance.mark() method.】
performanceMark.detail#>
- 类型: <any>
使用 Performance.mark() 方法创建时指定的附加详情。
【Additional detail specified when creating with Performance.mark() method.】
类:PerformanceMeasure#>
【Class: PerformanceMeasure】
公开通过 Performance.measure() 方法创建的指标。
【Exposes measures created via the Performance.measure() method.】
此类的构造函数不直接暴露给用户。
【The constructor of this class is not exposed to users directly.】
performanceMeasure.detail#>
- 类型: <any>
使用 Performance.measure() 方法创建时指定的附加详情。
【Additional detail specified when creating with Performance.measure() method.】
类:PerformanceNodeEntry#>
【Class: PerformanceNodeEntry】
该类是 Node.js 的一个扩展。在网页浏览器中不可用。
【This class is an extension by Node.js. It is not available in Web browsers.】
提供详细的 Node.js 时序数据。
【Provides detailed Node.js timing data.】
此类的构造函数不直接暴露给用户。
【The constructor of this class is not exposed to users directly.】
performanceNodeEntry.detail#>
- 类型: <any>
entryType 特有的附加细节。
【Additional detail specific to the entryType.】
performanceNodeEntry.flags#>
performanceNodeEntry.detail。- 类型: <number>
当 performanceEntry.entryType 等于 'gc' 时,performance.flags 属性包含有关垃圾回收操作的附加信息。其值可能为以下之一:
【When performanceEntry.entryType is equal to 'gc', the performance.flags
property contains additional information about garbage collection operation.
The value may be one of:】
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
performanceNodeEntry.kind#>
performanceNodeEntry.detail。- 类型: <number>
当 performanceEntry.entryType 等于 'gc' 时,performance.kind 属性会标识发生的垃圾回收操作类型。其值可能是以下之一:
【When performanceEntry.entryType is equal to 'gc', the performance.kind
property identifies the type of garbage collection operation that occurred.
The value may be one of:】
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
垃圾回收('gc')详情#>
【Garbage Collection ('gc') Details】
当 performanceEntry.type 等于 'gc' 时,performanceNodeEntry.detail 属性将是一个具有两个属性的 <Object>:
【When performanceEntry.type is equal to 'gc', the
performanceNodeEntry.detail property will be an <Object> with two properties:】
kind<number> 其中之一:perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
flags<number> 其中之一:perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
HTTP('http')详情#>
【HTTP ('http') Details】
当 performanceEntry.type 等于 'http' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
【When performanceEntry.type is equal to 'http', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.】
如果 performanceEntry.name 等于 HttpClient,detail 将包含以下属性:req、res。其中 req 属性将是一个 <Object>,包含 method、url、headers,而 res 属性将是一个 <Object>,包含 statusCode、statusMessage、headers。
【If performanceEntry.name is equal to HttpClient, the detail
will contain the following properties: req, res. And the req property
will be an <Object> containing method, url, headers, the res property
will be an <Object> containing statusCode, statusMessage, headers.】
如果 performanceEntry.name 等于 HttpRequest,detail 将包含以下属性:req、res。其中 req 属性将是一个 <Object>,包含 method、url、headers,而 res 属性将是一个 <Object>,包含 statusCode、statusMessage、headers。
【If performanceEntry.name is equal to HttpRequest, the detail
will contain the following properties: req, res. And the req property
will be an <Object> containing method, url, headers, the res property
will be an <Object> containing statusCode, statusMessage, headers.】
这可能会增加额外的内存开销,应仅用于诊断目的,不应在生产环境中默认开启。
【This could add additional memory overhead and should only be used for diagnostic purposes, not left turned on in production by default.】
HTTP/2('http2')详情#>
【HTTP/2 ('http2') Details】
当 performanceEntry.type 等于 'http2' 时,performanceNodeEntry.detail 属性将是一个包含额外性能信息的 <Object>。
【When performanceEntry.type is equal to 'http2', the
performanceNodeEntry.detail property will be an <Object> containing
additional performance information.】
如果 performanceEntry.name 等于 Http2Stream,detail 将包含以下属性:
【If performanceEntry.name is equal to Http2Stream, the detail
will contain the following properties:】
bytesRead<number> 接收到此Http2Stream的DATA帧字节数。bytesWritten<number> 发送此Http2Stream的DATA帧字节数。id<number> 关联的Http2Stream的标识符。timeToFirstByte<number> 从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> 表示Http2Session类型,可为'server'或'client'。
Timerify('函数')详情#>
【Timerify ('function') Details】
当 performanceEntry.type 等于 'function' 时,performanceNodeEntry.detail 属性将是一个 <Array>,列出被计时函数的输入参数。
【When performanceEntry.type is equal to 'function', the
performanceNodeEntry.detail property will be an <Array> listing
the input arguments to the timed function.】
净额('净额')详情#>
【Net ('net') Details】
当 performanceEntry.type 等于 'net' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
【When performanceEntry.type is equal to 'net', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.】
如果 performanceEntry.name 等于 connect,detail 将包含以下属性:host、port。
【If performanceEntry.name is equal to connect, the detail
will contain the following properties: host, port.】
DNS('dns')详细信息#>
【DNS ('dns') Details】
当 performanceEntry.type 等于 'dns' 时,performanceNodeEntry.detail 属性将是一个 <Object>,其中包含额外信息。
【When performanceEntry.type is equal to 'dns', the
performanceNodeEntry.detail property will be an <Object> containing
additional information.】
如果 performanceEntry.name 等于 lookup,则 detail 将包含以下属性:hostname、family、hints、verbatim、addresses。
【If performanceEntry.name is equal to lookup, the detail
will contain the following properties: hostname, family, hints, verbatim,
addresses.】
如果 performanceEntry.name 等于 lookupService,则 detail 将包含以下属性:host、port、hostname、service。
【If performanceEntry.name is equal to lookupService, the detail will
contain the following properties: host, port, hostname, service.】
如果 performanceEntry.name 等于 queryxxx 或 getHostByAddr,则 detail 将包含以下属性:host、ttl、result。result 的值与 queryxxx 或 getHostByAddr 的结果相同。
【If performanceEntry.name is equal to queryxxx or getHostByAddr, the detail will
contain the following properties: host, ttl, result. The value of result is
same as the result of queryxxx or getHostByAddr.】
类:PerformanceNodeTiming#>
【Class: PerformanceNodeTiming】
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
【This property is an extension by Node.js. It is not available in Web browsers.】
提供 Node.js 本身的时间详情。该类的构造函数不向用户公开。
【Provides timing details for Node.js itself. The constructor of this class is not exposed to users.】
performanceNodeTiming.bootstrapComplete#>
- 类型: <number>
Node.js 进程完成引导的高分辨率毫秒时间戳。如果引导尚未完成,该属性的值为 -1。
【The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1.】
performanceNodeTiming.environment#>
- 类型: <number>
Node.js 环境初始化时的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp at which the Node.js environment was initialized.】
performanceNodeTiming.idleTime#>
- 类型: <number>
事件循环在其事件提供者(例如 epoll_wait)中空闲的高分辨率毫秒时间戳。这不考虑 CPU 使用情况。如果事件循环尚未启动(例如,在主脚本的第一个时钟周期中),该属性的值为 0。
【The high resolution millisecond timestamp of the amount of time the event loop
has been idle within the event loop's event provider (e.g. epoll_wait). This
does not take CPU usage into consideration. If the event loop has not yet
started (e.g., in the first tick of the main script), the property has the
value of 0.】
performanceNodeTiming.loopExit#>
- 类型: <number>
Node.js 事件循环退出的高分辨率毫秒时间戳。如果事件循环尚未退出,该属性的值为 -1。只有在 'exit' 事件的处理程序中,该值才可能不是 -1。
【The high resolution millisecond timestamp at which the Node.js event loop
exited. If the event loop has not yet exited, the property has the value of -1.
It can only have a value of not -1 in a handler of the 'exit' event.】
performanceNodeTiming.loopStart#>
- 类型: <number>
Node.js 事件循环开始的高精度毫秒时间戳。如果事件循环尚未开始(例如,在主脚本的第一次迭代中),该属性的值为 -1。
【The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1.】
performanceNodeTiming.nodeStart#>
- 类型: <number>
Node.js 进程初始化时的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp at which the Node.js process was initialized.】
performanceNodeTiming.uvMetricsInfo#>
- 返回值: <Object>
这是 uv_metrics_info 函数的封装。它返回当前的一组事件循环指标。
【This is a wrapper to the uv_metrics_info function.
It returns the current set of event loop metrics.】
建议在使用 setImmediate 安排执行的函数中使用此属性,以避免在完成当前循环迭代期间安排的所有操作之前收集指标。
【It is recommended to use this property inside a function whose execution was
scheduled using setImmediate to avoid collecting metrics before finishing all
operations scheduled during the current loop iteration.】
const { performance } = require('node:perf_hooks');
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfo);
});import { performance } from 'node:perf_hooks';
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfo);
});
performanceNodeTiming.v8Start#>
- 类型: <number>
V8 平台初始化时的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp at which the V8 platform was initialized.】
类:PerformanceResourceTiming#>
【Class: PerformanceResourceTiming】
提供有关应用资源加载的详细网络时间数据。
【Provides detailed network timing data regarding the loading of an application's resources.】
此类的构造函数不直接暴露给用户。
【The constructor of this class is not exposed to users directly.】
performanceResourceTiming.workerStart#>
- 类型: <number>
在调度 fetch 请求之前的高分辨率毫秒时间戳。如果资源未被 worker 拦截,则该属性始终返回 0。
【The high resolution millisecond timestamp at immediately before dispatching
the fetch request. If the resource is not intercepted by a worker the property
will always return 0.】
performanceResourceTiming.redirectStart#>
- 类型: <number>
表示启动重定向的抓取开始时间的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp that represents the start time of the fetch which initiates the redirect.】
performanceResourceTiming.redirectEnd#>
- 类型: <number>
在接收到最后一次重定向的响应的最后一个字节后立即创建的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp that will be created immediately after receiving the last byte of the response of the last redirect.】
performanceResourceTiming.fetchStart#>
- 类型: <number>
在 Node.js 开始获取资源之前的高分辨率毫秒时间戳。
【The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource.】
performanceResourceTiming.domainLookupStart#>
- 类型: <number>
在 Node.js 开始为资源进行域名查找之前的高精度毫秒时间戳。
【The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup for the resource.】
performanceResourceTiming.domainLookupEnd#>
- 类型: <number>
高分辨率毫秒时间戳,表示 Node.js 完成资源的域名查询后立即的时间。
【The high resolution millisecond timestamp representing the time immediately after the Node.js finished the domain name lookup for the resource.】
performanceResourceTiming.connectStart#>
- 类型: <number>
高分辨率毫秒时间戳,表示 Node.js 在开始建立与服务器的连接以获取资源之前的时间。
【The high resolution millisecond timestamp representing the time immediately before Node.js starts to establish the connection to the server to retrieve the resource.】
performanceResourceTiming.connectEnd#>
- 类型: <number>
高精度毫秒时间戳,表示 Node.js 完成与服务器建立连接以获取资源后立即的时间。
【The high resolution millisecond timestamp representing the time immediately after Node.js finishes establishing the connection to the server to retrieve the resource.】
performanceResourceTiming.secureConnectionStart#>
- 类型: <number>
高分辨率毫秒时间戳,表示 Node.js 在开始握手以保护当前连接之前的时间。
【The high resolution millisecond timestamp representing the time immediately before Node.js starts the handshake process to secure the current connection.】
performanceResourceTiming.requestStart#>
- 类型: <number>
高精度毫秒时间戳,表示 Node.js 在接收到服务器响应的第一个字节之前的时间。
【The high resolution millisecond timestamp representing the time immediately before Node.js receives the first byte of the response from the server.】
performanceResourceTiming.responseEnd#>
- 类型: <number>
高精度毫秒时间戳,表示在 Node.js 接收到资源的最后一个字节后或在传输连接关闭前(以先发生者为准)的时间。
【The high resolution millisecond timestamp representing the time immediately after Node.js receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.】
performanceResourceTiming.transferSize#>
- 类型: <number>
表示获取的资源大小(以字节为单位)的数字。大小包括响应头字段以及响应负载主体。
【A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body.】
performanceResourceTiming.encodedBodySize#>
- 类型: <number>
表示从 fetch(HTTP 或缓存)接收的有效负载主体大小(以字节为单位)的数字,单位是在去除任何应用的内容编码之前。
【A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content-codings.】
performanceResourceTiming.decodedBodySize#>
- 类型: <number>
表示从 fetch(HTTP 或缓存)接收的消息主体的大小(以字节为单位)的数字,已去除任何应用的内容编码。
【A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after removing any applied content-codings.】
performanceResourceTiming.toJSON()#>
返回一个 object,它是 PerformanceResourceTiming 对象的 JSON 表示
【Returns a object that is the JSON representation of the
PerformanceResourceTiming object】
类:PerformanceObserver#>
【Class: PerformanceObserver】
PerformanceObserver.supportedEntryTypes#>
- 类型: <string[]>
获取支持的类型。
【Get supported types.】
new PerformanceObserver(callback)#>
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> 如果为 true,观察者回调将使用全局PerformanceEntry缓冲条目的列表调用。如果为 false,则只会将时间点之后创建的PerformanceEntry发送给观察者回调。默认值:false。
将 <PerformanceObserver> 实例订阅到新 <PerformanceEntry> 实例的通知,这些实例可以通过 options.entryTypes 或 options.type 标识:
【Subscribes the <PerformanceObserver> instance to notifications of new
<PerformanceEntry> instances identified either by options.entryTypes
or options.type:】
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((list, observer) => {
// Called once asynchronously. `list` contains three items.
});
obs.observe({ type: 'mark' });
for (let n = 0; n < 3; n++)
performance.mark(`test${n}`);const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((list, observer) => {
// Called once asynchronously. `list` contains three items.
});
obs.observe({ type: 'mark' });
for (let n = 0; n < 3; n++)
performance.mark(`test${n}`);
performanceObserver.takeRecords()#>
- 返回值: <PerformanceEntry[]> 当前存储在性能监视器中的条目列表,读取后将其清空。
类:PerformanceObserverEntryList#>
【Class: PerformanceObserverEntryList】
PerformanceObserverEntryList 类用于提供对传递给 PerformanceObserver 的 PerformanceEntry 实例的访问。该类的构造函数不对用户开放。
【The PerformanceObserverEntryList class is used to provide access to the
PerformanceEntry instances passed to a PerformanceObserver.
The constructor of this class is not exposed to users.】
performanceObserverEntryList.getEntries()#>
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。
【Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime.】
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntries());
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntries());
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');
performanceObserverEntryList.getEntriesByName(name[, type])#>
name<string>type<string>- 返回值: <PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.name 等于 name,并且可选地,performanceEntry.entryType 等于 type。
【Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.name is
equal to name, and optionally, whose performanceEntry.entryType is equal to
type.】
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByName('meow'));
/**
* [
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 98.545991,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('nope')); // []
console.log(perfObserverList.getEntriesByName('test', 'mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 63.518931,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['mark', 'measure'] });
performance.mark('test');
performance.mark('meow');const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByName('meow'));
/**
* [
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 98.545991,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('nope')); // []
console.log(perfObserverList.getEntriesByName('test', 'mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 63.518931,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['mark', 'measure'] });
performance.mark('test');
performance.mark('meow');
performanceObserverEntryList.getEntriesByType(type)#>
type<string>- 返回: <PerformanceEntry[]>
返回一个按时间顺序排列的 PerformanceEntry 对象列表,顺序基于 performanceEntry.startTime,且这些对象的 performanceEntry.entryType 等于 type。
【Returns a list of PerformanceEntry objects in chronological order
with respect to performanceEntry.startTime whose performanceEntry.entryType
is equal to type.】
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByType('mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 55.897834,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 56.350146,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByType('mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 55.897834,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 56.350146,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');
perf_hooks.createHistogram([options])#>
options<Object>
返回一个 <RecordableHistogram>。
【Returns a <RecordableHistogram>.】
perf_hooks.monitorEventLoopDelay([options])#>
options<Object>resolution<number> 采样率,以毫秒为单位。必须大于零。默认值:10。
- 返回值:<IntervalHistogram>
此属性是 Node.js 的扩展。在 Web 浏览器中不可用。
【This property is an extension by Node.js. It is not available in Web browsers.】
创建一个 IntervalHistogram 对象,用于随时间采样并报告事件循环延迟。延迟将以纳秒为单位报告。
【Creates an IntervalHistogram object that samples and reports the event loop
delay over time. The delays will be reported in nanoseconds.】
使用定时器检测事件循环的近似延迟之所以有效,是因为定时器的执行与 libuv 事件循环的生命周期紧密相关。也就是说,循环中的延迟会导致定时器执行的延迟,而这些延迟正是该 API 旨在检测的对象。
【Using a timer to detect approximate event loop delay works because the execution of timers is tied specifically to the lifecycle of the libuv event loop. That is, a delay in the loop will cause a delay in the execution of the timer, and those delays are specifically what this API is intended to detect.】
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));const { monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));
类:Histogram#>
【Class: Histogram】
histogram.count#>
- 类型: <number>
直方图记录的样本数。
【The number of samples recorded by the histogram.】
histogram.countBigInt#>
- 类型: <bigint>
直方图记录的样本数。
【The number of samples recorded by the histogram.】
histogram.exceeds#>
- 类型: <number>
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
【The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.】
histogram.exceedsBigInt#>
- 类型: <bigint>
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
【The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.】
histogram.max#>
- 类型: <number>
记录的事件循环延迟的最大值。
【The maximum recorded event loop delay.】
histogram.maxBigInt#>
- 类型: <bigint>
记录的事件循环延迟的最大值。
【The maximum recorded event loop delay.】
histogram.mean#>
- 类型: <number>
记录的事件循环延迟的平均值。
【The mean of the recorded event loop delays.】
histogram.min#>
- 类型: <number>
记录的事件循环延迟的最小值。
【The minimum recorded event loop delay.】
histogram.minBigInt#>
- 类型: <bigint>
记录的事件循环延迟的最小值。
【The minimum recorded event loop delay.】
histogram.percentile(percentile)#>
返回给定的百分位数的值。
【Returns the value at the given percentile.】
histogram.percentileBigInt(percentile)#>
返回给定的百分位数的值。
【Returns the value at the given percentile.】
histogram.percentiles#>
- 类型: <Map>
返回一个 Map 对象,详细说明累计百分比分布。
【Returns a Map object detailing the accumulated percentile distribution.】
histogram.percentilesBigInt#>
- 类型: <Map>
返回一个 Map 对象,详细说明累计百分比分布。
【Returns a Map object detailing the accumulated percentile distribution.】
histogram.reset()#>
重置收集的直方图数据。
【Resets the collected histogram data.】
histogram.stddev#>
- 类型: <number>
记录的事件循环延迟的标准偏差。
【The standard deviation of the recorded event loop delays.】
类:IntervalHistogram 继承自 Histogram#>
【Class: IntervalHistogram extends Histogram】
一个按给定时间间隔定期更新的 直方图。
【A Histogram that is periodically updated on a given interval.】
histogram.disable()#>
- 返回: <boolean>
禁用更新间隔定时器。如果定时器已停止,返回 true;如果定时器已经停止,则返回 false。
【Disables the update interval timer. Returns true if the timer was
stopped, false if it was already stopped.】
histogram.enable()#>
- 返回: <boolean>
启用更新间隔定时器。如果定时器已启动,则返回 false;如果定时器刚启动,则返回 true。
【Enables the update interval timer. Returns true if the timer was
started, false if it was already started.】
克隆 IntervalHistogram#>
【Cloning an IntervalHistogram】
<IntervalHistogram> 实例可以通过 <MessagePort> 进行克隆。在接收端,直方图会被克隆为一个普通的 <Histogram> 对象,该对象不实现 enable() 和 disable() 方法。
类:RecordableHistogram 继承自 Histogram#>
【Class: RecordableHistogram extends Histogram】
histogram.add(other)#>
other<RecordableHistogram>
将 other 中的值添加到此直方图中。
【Adds the values from other to this histogram.】
histogram.record(val)#>
histogram.recordDelta()#>
计算自上一次调用 recordDelta() 以来经过的时间(以纳秒为单位),并将该时间记录到直方图中。
【Calculates the amount of time (in nanoseconds) that has passed since the
previous call to recordDelta() and records that amount in the histogram.】
示例#>
【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);'use strict';
const async_hooks = require('node:async_hooks');
const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const set = new Set();
const hook = async_hooks.createHook({
init(id, type) {
if (type === 'Timeout') {
performance.mark(`Timeout-${id}-Init`);
set.add(id);
}
},
destroy(id) {
if (set.has(id)) {
set.delete(id);
performance.mark(`Timeout-${id}-Destroy`);
performance.measure(`Timeout-${id}`,
`Timeout-${id}-Init`,
`Timeout-${id}-Destroy`);
}
},
});
hook.enable();
const obs = new PerformanceObserver((list, observer) => {
console.log(list.getEntries()[0]);
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['measure'] });
setTimeout(() => {}, 1000);
测量加载依赖需要多长时间#>
【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');'use strict';
const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const mod = require('node:module');
// Monkey patch the require function
mod.Module.prototype.require =
performance.timerify(mod.Module.prototype.require);
require = performance.timerify(require);
// Activate the observer
const obs = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
console.log(`require('${entry[0]}')`, entry.duration);
});
performance.clearMarks();
performance.clearMeasures();
obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });
require('some-module');
测量一次 HTTP 往返需要多长时间#>
【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}`);
});'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const http = require('node:http');
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((item) => {
console.log(item);
});
});
obs.observe({ entryTypes: ['http'] });
const PORT = 8080;
http.createServer((req, res) => {
res.end('ok');
}).listen(PORT, () => {
http.get(`http://127.0.0.1:${PORT}`);
});
测量在连接成功时 net.connect(仅适用于 TCP)所耗费的时间#>
【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);
});'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const net = require('node:net');
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((item) => {
console.log(item);
});
});
obs.observe({ entryTypes: ['net'] });
const PORT = 8080;
net.createServer((socket) => {
socket.destroy();
}).listen(PORT, () => {
net.connect(PORT);
});
测量请求成功时 DNS 花费的时间#>
【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');'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const dns = require('node:dns');
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((item) => {
console.log(item);
});
});
obs.observe({ entryTypes: ['dns'] });
dns.lookup('localhost', () => {});
dns.promises.resolve('localhost');