Node.js v25.0.0 文档
- Node.js v25.0.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 extends Histogram - 类:
RecordableHistogram extends Histogram - 示例
- 性能测量 API
-
索引
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:moduleAPI - 模块:包
- 模块:TypeScript
- 网络
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- 其他版本
- 选项
性能测量 API#
源代码: lib/perf_hooks.js
此模块提供了 W3C Web 性能 API 的一个子集的实现,以及用于 Node.js 特定性能测量的额外 API。
Node.js 支持以下 Web 性能 API
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
performance.clearMarks();
});
obs.observe({ type: 'measure' });
performance.measure('Start to Now');
performance.mark('A');
doSomeLongRunningProcess(() => {
performance.measure('A to Now', 'A');
performance.mark('B');
performance.measure('A to B', 'A', 'B');
});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。
performance.clearMarks([name])#
name<string>
如果未提供 name,则从性能时间线中移除所有 PerformanceMark 对象。如果提供了 name,则仅移除指定名称的标记。
performance.clearMeasures([name])#
name<string>
如果未提供 name,则从性能时间线中移除所有 PerformanceMeasure 对象。如果提供了 name,则仅移除指定名称的度量。
performance.clearResourceTimings([name])#
name<string>
如果未提供 name,则从资源时间线中移除所有 PerformanceResourceTiming 对象。如果提供了 name,则仅移除指定名称的资源。
performance.eventLoopUtilization([utilization1[, utilization2]])#
utilization1<Object> 上一次调用eventLoopUtilization()的结果。utilization2<Object> 在utilization1之前调用eventLoopUtilization()的结果。- 返回:<Object>
eventLoopUtilization() 方法返回一个对象,该对象包含事件循环处于空闲和活动状态的累积持续时间,以高精度毫秒计时器表示。utilization 值是计算出的事件循环利用率 (ELU)。
如果主线程上的引导尚未完成,这些属性的值为 0。ELU 在工作线程上立即可用,因为引导过程在事件循环内发生。
utilization1 和 utilization2 都是可选参数。
如果传入了 utilization1,则会计算并返回当前调用与 utilization1 之间的 active 和 idle 时间的差值,以及相应的 utilization 值(类似于 process.hrtime())。
如果同时传入了 utilization1 和 utilization2,则会计算这两个参数之间的差值。这是一个方便的选项,因为与 process.hrtime() 不同,计算 ELU 比单个减法更复杂。
ELU 类似于 CPU 利用率,但它只测量事件循环的统计数据,而不是 CPU 使用率。它表示事件循环在事件循环的事件提供者(例如 epoll_wait)之外所花费的时间百分比。不考虑其他 CPU 空闲时间。以下是一个例子,说明一个大部分时间空闲的进程如何具有较高的 ELU。
import { eventLoopUtilization } from 'node:perf_hooks';
import { spawnSync } from 'node:child_process';
setImmediate(() => {
const elu = eventLoopUtilization();
spawnSync('sleep', ['5']);
console.log(eventLoopUtilization(elu).utilization);
});'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() 的调用阻塞了事件循环的进行。
传入用户定义的对象而不是上一次调用 eventLoopUtilization() 的结果将导致未定义的行为。返回值不保证反映事件循环的任何正确状态。
performance.getEntries()#
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。如果您只对特定类型或具有特定名称的性能条目感兴趣,请参阅 performance.getEntriesByType() 和 performance.getEntriesByName()。
performance.getEntriesByName(name[, type])#
name<string>type<string>- 返回:<PerformanceEntry[]>
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.name 等于 name,并且可选地,其 performanceEntry.entryType 等于 type。
performance.getEntriesByType(type)#
type<string>- 返回:<PerformanceEntry[]>
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.entryType 等于 type。
performance.mark(name[, options])#
在性能时间线中创建一个新的 PerformanceMark 条目。PerformanceMark 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'mark',performanceEntry.duration 始终为 0。性能标记用于在性能时间线中标记特定的重要时刻。
创建的 PerformanceMark 条目被放入全局性能时间线中,并可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当观察完成后,应使用 performance.clearMarks 手动从全局性能时间线中清除这些条目。
performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode, bodyInfo, responseStatus[, deliveryType])#
timingInfo<Object> 获取计时信息requestedUrl<string> 资源 URLinitiatorType<string> 发起者名称,例如:'fetch'global<Object>cacheMode<string> 缓存模式必须是空字符串 ('') 或 'local'bodyInfo<Object> 获取响应体信息responseStatus<number> 响应的状态码deliveryType<string> 交付类型。默认值:''。
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
在资源时间线中创建一个新的 PerformanceResourceTiming 条目。PerformanceResourceTiming 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'resource'。性能资源用于标记资源时间线中的时刻。
创建的 PerformanceMark 条目被放入全局资源时间线中,并可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当观察完成后,应使用 performance.clearResourceTimings 手动从全局性能时间线中清除这些条目。
performance.measure(name[, startMarkOrOptions[, endMark]])#
name<string>startMarkOrOptions<string> | <Object> 可选。endMark<string> 可选。如果startMarkOrOptions是一个 <Object>,则必须省略。
在性能时间线中创建一个新的 PerformanceMeasure 条目。PerformanceMeasure 是 PerformanceEntry 的子类,其 performanceEntry.entryType 始终为 'measure',其 performanceEntry.duration 测量自 startMark 和 endMark 以来经过的毫秒数。
startMark 参数可以标识性能时间线中的任何现有 PerformanceMark,或者可以标识 PerformanceNodeTiming 类提供的任何时间戳属性。如果指定的 startMark 不存在,则会抛出错误。
可选的 endMark 参数必须标识性能时间线中的任何现有 PerformanceMark 或 PerformanceNodeTiming 类提供的任何时间戳属性。如果没有传递参数,endMark 将是 performance.now(),否则如果指定的 endMark 不存在,将抛出错误。
创建的 PerformanceMeasure 条目被放入全局性能时间线中,并可以通过 performance.getEntries、performance.getEntriesByName 和 performance.getEntriesByType 进行查询。当观察完成后,应使用 performance.clearMeasures 手动从全局性能时间线中清除这些条目。
performance.nodeTiming#
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
PerformanceNodeTiming 类的一个实例,为特定的 Node.js 操作里程碑提供性能指标。
performance.setResourceTimingBufferSize(maxSize)#
将全局性能资源计时缓冲区大小设置为指定数量的“resource”类型性能条目对象。
默认情况下,最大缓冲区大小设置为 250。
performance.timerify(fn[, options])#
fn<Function>options<Object>histogram<RecordableHistogram> 一个使用perf_hooks.createHistogram()创建的直方图对象,它将以纳秒为单位记录运行时长。
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
将一个函数包装在一个新函数中,该新函数测量被包装函数的运行时间。必须有一个 PerformanceObserver 订阅 'function' 事件类型,才能访问计时细节。
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,一个 finally 处理程序将被附加到该 promise 上,并且在 finally 处理程序被调用后报告持续时间。
performance.toJSON()#
一个对象,是 performance 对象的 JSON 表示。它类似于浏览器中的 window.performance.toJSON。
事件:'resourcetimingbufferfull'#
当全局性能资源计时缓冲区已满时,会触发 'resourcetimingbufferfull' 事件。在事件监听器中,使用 performance.setResourceTimingBufferSize() 调整资源计时缓冲区大小或使用 performance.clearResourceTimings() 清除缓冲区,以允许更多条目被添加到性能时间线缓冲区。
类:PerformanceEntry#
此类的构造函数不会直接暴露给用户。
类:PerformanceMark#
暴露通过 Performance.mark() 方法创建的标记。
类:PerformanceMeasure#
暴露通过 Performance.measure() 方法创建的度量。
此类的构造函数不会直接暴露给用户。
类:PerformanceNodeEntry#
此类是 Node.js 的扩展。它在 Web 浏览器中不可用。
提供详细的 Node.js 计时数据。
此类的构造函数不会直接暴露给用户。
performanceNodeEntry.flags#
performanceNodeEntry.detail。- 类型:<number>
当 performanceEntry.entryType 等于 'gc' 时,performance.flags 属性包含有关垃圾回收操作的附加信息。该值可以是以下之一:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
performanceNodeEntry.kind#
performanceNodeEntry.detail。- 类型:<number>
当 performanceEntry.entryType 等于 'gc' 时,performance.kind 属性标识发生的垃圾回收操作的类型。该值可以是以下之一:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
垃圾回收 ('gc') 详情#
当 performanceEntry.type 等于 'gc' 时,performanceNodeEntry.detail 属性将是一个具有两个属性的 <Object>:
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') 详情#
当 performanceEntry.type 等于 'http' 时,performanceNodeEntry.detail 属性将是一个包含附加信息的 <Object>。
如果 performanceEntry.name 等于 HttpClient,detail 将包含以下属性:req、res。并且 req 属性将是一个包含 method、url、headers 的 <Object>,res 属性将是一个包含 statusCode、statusMessage、headers 的 <Object>。
如果 performanceEntry.name 等于 HttpRequest,detail 将包含以下属性:req、res。并且 req 属性将是一个包含 method、url、headers 的 <Object>,res 属性将是一个包含 statusCode、statusMessage、headers 的 <Object>。
这可能会增加额外的内存开销,应仅用于诊断目的,不应在生产环境中默认开启。
HTTP/2 ('http2') 详情#
当 performanceEntry.type 等于 'http2' 时,performanceNodeEntry.detail 属性将是一个包含附加性能信息的 <Object>。
如果 performanceEntry.name 等于 Http2Stream,detail 将包含以下属性:
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 将包含以下属性:
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的类型。
计时器化 ('function') 详情#
当 performanceEntry.type 等于 'function' 时,performanceNodeEntry.detail 属性将是一个 <Array>,列出计时函数的输入参数。
网络 ('net') 详情#
当 performanceEntry.type 等于 'net' 时,performanceNodeEntry.detail 属性将是一个包含附加信息的 <Object>。
如果 performanceEntry.name 等于 connect,detail 将包含以下属性:host、port。
DNS ('dns') 详情#
当 performanceEntry.type 等于 'dns' 时,performanceNodeEntry.detail 属性将是一个包含附加信息的 <Object>。
如果 performanceEntry.name 等于 lookup,detail 将包含以下属性:hostname、family、hints、verbatim、addresses。
如果 performanceEntry.name 等于 lookupService,detail 将包含以下属性:host、port、hostname、service。
如果 performanceEntry.name 等于 queryxxx 或 getHostByAddr,detail 将包含以下属性:host、ttl、result。result 的值与 queryxxx 或 getHostByAddr 的结果相同。
类:PerformanceNodeTiming#
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
提供 Node.js 本身的计时细节。此类的构造函数不会直接暴露给用户。
performanceNodeTiming.idleTime#
- 类型:<number>
事件循环在其事件提供者(例如 epoll_wait)内处于空闲状态的时间量的高精度毫秒时间戳。这不考虑 CPU 使用情况。如果事件循环尚未启动(例如,在主脚本的第一个 tick 中),该属性的值为 0。
performanceNodeTiming.loopExit#
- 类型:<number>
Node.js 事件循环退出的高精度毫秒时间戳。如果事件循环尚未退出,该属性的值为 -1。它只能在 'exit' 事件的处理程序中具有非 -1 的值。
performanceNodeTiming.loopStart#
- 类型:<number>
Node.js 事件循环启动的高精度毫秒时间戳。如果事件循环尚未启动(例如,在主脚本的第一个 tick 中),该属性的值为 -1。
performanceNodeTiming.uvMetricsInfo#
- 返回:<Object>
这是对 uv_metrics_info 函数的包装。它返回当前的事件循环指标集。
建议在通过 setImmediate 调度的函数内部使用此属性,以避免在完成当前循环迭代期间所有计划的操作之前收集指标。
const { performance } = require('node:perf_hooks');
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfo);
});import { performance } from 'node:perf_hooks';
setImmediate(() => {
console.log(performance.nodeTiming.uvMetricsInfo);
});
类:PerformanceResourceTiming#
提供有关应用程序资源加载的详细网络计时数据。
此类的构造函数不会直接暴露给用户。
performanceResourceTiming.workerStart#
- 类型:<number>
在分派 fetch 请求之前立即的高精度毫秒时间戳。如果资源未被工作线程拦截,该属性将始终返回 0。
performanceResourceTiming.secureConnectionStart#
- 类型:<number>
代表 Node.js 开始握手过程以保护当前连接之前立即的时间的高精度毫秒时间戳。
performanceResourceTiming.responseEnd#
- 类型:<number>
代表 Node.js 接收到资源的最后一个字节之后立即,或在传输连接关闭之前立即的时间的高精度毫秒时间戳,以先到者为准。
performanceResourceTiming.encodedBodySize#
- 类型:<number>
表示从获取(HTTP 或缓存)中接收到的有效载荷主体的大小(以八位字节为单位),在移除任何应用的内容编码之前。
performanceResourceTiming.decodedBodySize#
- 类型:<number>
表示从获取(HTTP 或缓存)中接收到的消息主体的大小(以八位字节为单位),在移除任何应用的内容编码之后。
performanceResourceTiming.toJSON()#
返回一个 object,它是 PerformanceResourceTiming 对象的 JSON 表示
类:PerformanceObserver#
new PerformanceObserver(callback)#
callback<Function>list<PerformanceObserverEntryList>observer<PerformanceObserver>
PerformanceObserver 对象在新的 PerformanceEntry 实例被添加到性能时间线时提供通知。
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((list, observer) => {
console.log(list.getEntries());
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['mark'], buffered: true });
performance.mark('test');const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((list, observer) => {
console.log(list.getEntries());
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['mark'], buffered: true });
performance.mark('test');
由于 PerformanceObserver 实例会引入额外的性能开销,实例不应无限期地订阅通知。用户应在不再需要观察者时立即断开连接。
当 PerformanceObserver 被通知有新的 PerformanceEntry 实例时,会调用 callback。回调函数会接收一个 PerformanceObserverEntryList 实例和对 PerformanceObserver 的引用。
performanceObserver.disconnect()#
断开 PerformanceObserver 实例与所有通知的连接。
performanceObserver.observe(options)#
options<Object>type<string> 单个 <PerformanceEntry> 类型。如果已指定entryTypes,则不得提供此项。entryTypes<string[]> 一个字符串数组,用于标识观察者感兴趣的 <PerformanceEntry> 实例的类型。如果未提供,将抛出错误。buffered<boolean> 如果为 true,则使用全局PerformanceEntry缓冲条目列表调用观察者回调。如果为 false,则只有在该时间点之后创建的PerformanceEntrys 会发送到观察者回调。默认值:false。
订阅 <PerformanceObserver> 实例,以接收由 options.entryTypes 或 options.type 标识的新 <PerformanceEntry> 实例的通知。
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#
PerformanceObserverEntryList 类用于提供对传递给 PerformanceObserver 的 PerformanceEntry 实例的访问。此类的构造函数不会直接暴露给用户。
performanceObserverEntryList.getEntries()#
返回一个按 performanceEntry.startTime 时间顺序排列的 PerformanceEntry 对象列表。
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntries());
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');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.startTime 时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.name 等于 name,并且可选地,其 performanceEntry.entryType 等于 type。
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByName('meow'));
/**
* [
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 98.545991,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('nope')); // []
console.log(perfObserverList.getEntriesByName('test', 'mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 63.518931,
* duration: 0,
* detail: null
* }
* ]
*/
console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['mark', 'measure'] });
performance.mark('test');
performance.mark('meow');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.startTime 时间顺序排列的 PerformanceEntry 对象列表,其 performanceEntry.entryType 等于 type。
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntriesByType('mark'));
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 55.897834,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 56.350146,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');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>
返回一个 <RecordableHistogram>。
perf_hooks.monitorEventLoopDelay([options])#
options<Object>resolution<number> 采样率(以毫秒为单位)。必须大于零。默认值:10。
- 返回:<IntervalHistogram>
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
创建一个 IntervalHistogram 对象,该对象随时间采样并报告事件循环延迟。延迟将以纳秒为单位报告。
使用计时器来检测近似的事件循环延迟是可行的,因为计时器的执行与 libuv 事件循环的生命周期特定地联系在一起。也就是说,循环中的延迟会导致计时器执行的延迟,而这些延迟正是此 API 旨在检测的。
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#
histogram.percentileBigInt(percentile)#
返回给定百分位的值。
histogram.reset()#
重置收集的直方图数据。
类:IntervalHistogram extends Histogram#
一个在给定间隔内定期更新的 Histogram。
histogram[Symbol.dispose]()#
在直方图被销毁时禁用更新间隔计时器。
const { monitorEventLoopDelay } = require('node:perf_hooks');
{
using hist = monitorEventLoopDelay({ resolution: 20 });
hist.enable();
// The histogram will be disabled when the block is exited.
}
克隆一个 IntervalHistogram#
<IntervalHistogram> 实例可以通过 <MessagePort> 进行克隆。在接收端,直方图被克隆为一个普通的 <Histogram> 对象,它不实现 enable() 和 disable() 方法。
类:RecordableHistogram extends Histogram#
histogram.recordDelta()#
计算自上次调用 recordDelta() 以来经过的时间(以纳秒为单位),并在直方图中记录该量。
示例#
测量异步操作的持续时间#
以下示例使用 Async Hooks 和 Performance API 来测量 Timeout 操作的实际持续时间(包括执行回调所需的时间)。
import { createHook } from 'node:async_hooks';
import { performance, PerformanceObserver } from 'node:perf_hooks';
const set = new Set();
const hook = createHook({
init(id, type) {
if (type === 'Timeout') {
performance.mark(`Timeout-${id}-Init`);
set.add(id);
}
},
destroy(id) {
if (set.has(id)) {
set.delete(id);
performance.mark(`Timeout-${id}-Destroy`);
performance.measure(`Timeout-${id}`,
`Timeout-${id}-Init`,
`Timeout-${id}-Destroy`);
}
},
});
hook.enable();
const obs = new PerformanceObserver((list, observer) => {
console.log(list.getEntries()[0]);
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ entryTypes: ['measure'], buffered: true });
setTimeout(() => {}, 1000);'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);
测量加载依赖项所需的时间#
以下示例测量 require() 操作加载依赖项的持续时间
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 往返所需的时间#
以下示例用于跟踪 HTTP 客户端 (OutgoingMessage) 和 HTTP 请求 (IncomingMessage) 所花费的时间。对于 HTTP 客户端,它表示从启动请求到接收响应的时间间隔,对于 HTTP 请求,它表示从接收请求到发送响应的时间间隔。
import { PerformanceObserver } from 'node:perf_hooks';
import { createServer, get } from 'node:http';
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((item) => {
console.log(item);
});
});
obs.observe({ entryTypes: ['http'] });
const PORT = 8080;
createServer((req, res) => {
res.end('ok');
}).listen(PORT, () => {
get(`http://127.0.0.1:${PORT}`);
});'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) 所需的时间#
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 所需的时间#
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');