- 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 域
- 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.11.0 文档
- Node.js v22.11.0
-
目录
- 性能测量 API
perf_hooks.performance
performance.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.nodeTiming
performance.now()
performance.setResourceTimingBufferSize(maxSize)
performance.timeOrigin
performance.timerify(fn[, options])
performance.toJSON()
- 类:
PerformanceEntry
- 类:
PerformanceMark
- 类:
PerformanceMeasure
- 类:
PerformanceNodeEntry
- 类:
PerformanceNodeTiming
- 类:
PerformanceResourceTiming
performanceResourceTiming.workerStart
performanceResourceTiming.redirectStart
performanceResourceTiming.redirectEnd
performanceResourceTiming.fetchStart
performanceResourceTiming.domainLookupStart
performanceResourceTiming.domainLookupEnd
performanceResourceTiming.connectStart
performanceResourceTiming.connectEnd
performanceResourceTiming.secureConnectionStart
performanceResourceTiming.requestStart
performanceResourceTiming.responseEnd
performanceResourceTiming.transferSize
performanceResourceTiming.encodedBodySize
performanceResourceTiming.decodedBodySize
performanceResourceTiming.toJSON()
- 类:
PerformanceObserver
- 类:
PerformanceObserverEntryList
perf_hooks.createHistogram([options])
perf_hooks.monitorEventLoopDelay([options])
- 类:
Histogram
histogram.count
histogram.countBigInt
histogram.exceeds
histogram.exceedsBigInt
histogram.max
histogram.maxBigInt
histogram.mean
histogram.min
histogram.minBigInt
histogram.percentile(percentile)
histogram.percentileBigInt(percentile)
histogram.percentiles
histogram.percentilesBigInt
histogram.reset()
histogram.stddev
- 类:
IntervalHistogram extends Histogram
- 类:
RecordableHistogram extends 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 域
- 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
¥Stability: 2 - Stable
源代码: lib/perf_hooks.js
该模块提供了 W3C 网络性能 API 子集的实现以及用于 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 支持以下 网络性能 API:
¥Node.js supports the following Web Performance APIs:
const { PerformanceObserver, performance } = require('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');
});
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()
的结果。¥
utilization1
<Object> The result of a previous call toeventLoopUtilization()
. -
utilization2
<Object> 在utilization1
之前调用eventLoopUtilization()
的结果。¥
utilization2
<Object> The result of a previous call toeventLoopUtilization()
prior toutilization1
. -
返回:<Object>
¥Returns: <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.
'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()
#
-
¥Returns: <PerformanceEntry[]>
返回 PerformanceEntry
对象的列表,按照相对于 performanceEntry.startTime
的时间顺序排列。如果你只对某些类型或具有某些名称的性能条目感兴趣,则参阅 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> -
¥Returns: <PerformanceEntry[]>
返回按时间顺序的 PerformanceEntry
对象列表,其中 performanceEntry.startTime
的 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> -
¥Returns: <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> Fetch Timing Info -
requestedUrl
<string> 资源网址¥
requestedUrl
<string> The resource url -
initiatorType
<string> 启动器名称,例如:'fetch'¥
initiatorType
<string> The initiator name, e.g: 'fetch' -
global
<Object> -
cacheMode
<string> 缓存模式必须是空字符串('')或 'local'¥
cacheMode
<string> The cache mode must be an empty string ('') or 'local' -
¥
bodyInfo
<Object> Fetch Response Body Info -
responseStatus
<number> 响应的状态代码¥
responseStatus
<number> The response's status code -
deliveryType
<string> 交付类型。默认值:''
。¥
deliveryType
<string> The delivery type. Default:''
.
此属性是 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> 可选的。¥
startMarkOrOptions
<string> | <Object> Optional.-
detail
<any> 要包含在度量中的其他可选细节。¥
detail
<any> Additional optional detail to include with the measure. -
duration
<number> 开始和结束时间之间的持续时间。¥
duration
<number> Duration between start and end times. -
end
<number> | <string> 用作结束时间的时间戳,或标识先前记录标记的字符串。¥
end
<number> | <string> Timestamp to be used as the end time, or a string identifying a previously recorded mark. -
start
<number> | <string> 用作开始时间的时间戳,或标识先前记录标记的字符串。¥
start
<number> | <string> Timestamp to be used as the start time, or a string identifying a previously recorded mark.
-
-
endMark
<string> 可选的。如果startMarkOrOptions
是 <Object>,则必须省略。¥
endMark
<string> Optional. Must be omitted ifstartMarkOrOptions
is an <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])
#
-
fn
<Function> -
options
<Object>-
histogram
<RecordableHistogram> 使用perf_hooks.createHistogram()
创建的直方图对象,以纳秒为单位记录运行时间。¥
histogram
<RecordableHistogram> A histogram object created usingperf_hooks.createHistogram()
that will record runtime durations in nanoseconds.
-
此属性是 Node.js 的扩展。它在 Web 浏览器中不可用。
¥This property is an extension by Node.js. It is not available in Web browsers.
将函数封装在测量被封装函数运行时间的新函数中。PerformanceObserver
必须订阅 'function'
事件类型才能访问时间细节。
¥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.
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 句柄就会报告持续时间。
¥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
#
此条目经过的总毫秒数。此值对所有性能条目类型都没有意义。
¥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)¥
'dns'
(Node.js only) -
'function'
(仅限 Node.js)¥
'function'
(Node.js only) -
'gc'
(仅限 Node.js)¥
'gc'
(Node.js only) -
'http2'
(仅限 Node.js)¥
'http2'
(Node.js only) -
'http'
(仅限 Node.js)¥
'http'
(Node.js only) -
'mark'
(在网络上可用)¥
'mark'
(available on the Web) -
'measure'
(在网络上可用)¥
'measure'
(available on the Web) -
'net'
(仅限 Node.js)¥
'net'
(Node.js only) -
'node'
(仅限 Node.js)¥
'node'
(Node.js only) -
'resource'
(在网络上可用)¥
'resource'
(available on the Web)
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
-
¥Extends: <PerformanceEntry>
公开通过 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
-
¥Extends: <PerformanceEntry>
公开通过 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
-
¥Extends: <PerformanceEntry>
此类是 Node.js 的扩展。它在 Web 浏览器中不可用。
¥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
#
performanceNodeEntry.detail
。¥Stability: 0 - Deprecated: Use performanceNodeEntry.detail
instead.
当 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
#
performanceNodeEntry.detail
。¥Stability: 0 - Deprecated: Use performanceNodeEntry.detail
instead.
当 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_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> 其中之一:¥
kind
<number> One of:-
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
-
perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
-
perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
-
perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
-
-
flags
<number> 其中之一:¥
flags
<number> 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
-
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
属性将是包含 method
、url
、headers
的 <Object>,res
属性将是包含 statusCode
、statusMessage
、headers
的 <Object>。
¥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
属性将是包含 method
、url
、headers
的 <Object>,res
属性将是包含 statusCode
、statusMessage
、headers
的 <Object>。
¥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
帧字节数。¥
bytesRead
<number> The number ofDATA
frame bytes received for thisHttp2Stream
. -
bytesWritten
<number> 为此Http2Stream
发送的DATA
帧字节数。¥
bytesWritten
<number> The number ofDATA
frame bytes sent for thisHttp2Stream
. -
id
<number> 关联Http2Stream
的标识符¥
id
<number> The identifier of the associatedHttp2Stream
-
timeToFirstByte
<number> 从PerformanceEntry
startTime
到接收到第一个DATA
帧之间经过的毫秒数。¥
timeToFirstByte
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and the reception of the firstDATA
frame. -
timeToFirstByteSent
<number> 从PerformanceEntry
startTime
到发送的第一个DATA
帧之间经过的毫秒数。¥
timeToFirstByteSent
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and sending of the firstDATA
frame. -
timeToFirstHeader
<number> 从PerformanceEntry
startTime
到接收到第一个标头之间经过的毫秒数。¥
timeToFirstHeader
<number> The number of milliseconds elapsed between thePerformanceEntry
startTime
and the reception of the first header.
如果 performanceEntry.name
等于 Http2Session
,则 detail
将包含以下属性:
¥If performanceEntry.name
is equal to Http2Session
, the detail
will
contain the following properties:
-
bytesRead
<number> 为此Http2Session
接收的字节数。¥
bytesRead
<number> The number of bytes received for thisHttp2Session
. -
bytesWritten
<number> 为此Http2Session
发送的字节数。¥
bytesWritten
<number> The number of bytes sent for thisHttp2Session
. -
framesReceived
<number>Http2Session
接收到的 HTTP/2 帧数。¥
framesReceived
<number> The number of HTTP/2 frames received by theHttp2Session
. -
framesSent
<number>Http2Session
发送的 HTTP/2 帧数。¥
framesSent
<number> The number of HTTP/2 frames sent by theHttp2Session
. -
maxConcurrentStreams
<number>Http2Session
生命周期内同时打开的最大流数。¥
maxConcurrentStreams
<number> The maximum number of streams concurrently open during the lifetime of theHttp2Session
. -
pingRTT
<number> 从发送PING
帧到接收到它的确认所经过的毫秒数。只有在Http2Session
上发送了PING
帧时才会出现。¥
pingRTT
<number> The number of milliseconds elapsed since the transmission of aPING
frame and the reception of its acknowledgment. Only present if aPING
frame has been sent on theHttp2Session
. -
streamAverageDuration
<number> 所有Http2Stream
实例的平均持续时间(以毫秒为单位)¥
streamAverageDuration
<number> The average duration (in milliseconds) for allHttp2Stream
instances. -
streamCount
<number>Http2Session
处理的Http2Stream
实例的数量。¥
streamCount
<number> The number ofHttp2Stream
instances processed by theHttp2Session
. -
type
<string>'server'
或'client'
来标识Http2Session
的类型。¥
type
<string> Either'server'
or'client'
to identify the type ofHttp2Session
.
定时器化 ('function') 详细信息#
¥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 ('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
-
¥Extends: <PerformanceEntry>
此属性是 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>
¥Returns: <Object>
-
loopCount
<number> 事件循环迭代次数。¥
loopCount
<number> Number of event loop iterations. -
events
<number> 事件处理程序已处理的事件数。¥
events
<number> Number of events that have been processed by the event handler. -
eventsWaiting
<number> 调用事件提供程序时等待处理的事件数。¥
eventsWaiting
<number> Number of events that were waiting to be processed when the event provider was called.
-
这是 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
#
V8 平台初始化的高解析度毫秒时间戳。
¥The high resolution millisecond timestamp at which the V8 platform was initialized.
类:PerformanceResourceTiming
#
¥Class: PerformanceResourceTiming
-
¥Extends: <PerformanceEntry>
提供有关应用资源加载的详细网络计时数据。
¥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
请求之前的高解析度毫秒时间戳。如果资源没有被工作进程截获,该属性将始终返回 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.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
#
表示在删除任何应用的内容编码之前从有效负载主体的提取(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
#
表示在删除任何应用的内容编码后,从消息主体的提取(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
#
获取支持的类型。
¥Get supported types.
new PerformanceObserver(callback)
#
-
callback
<Function>-
observer
<PerformanceObserver>
当新的 PerformanceEntry
实例被添加到性能时间线时,则 PerformanceObserver
对象会提供通知。
¥PerformanceObserver
objects provide notifications when new
PerformanceEntry
instances have been added to the Performance Timeline.
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.
当 PerformanceObserver
接收到有关新的 PerformanceEntry
实例的通知时,则会调用 callback
。回调接收到 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
,则不能给出。¥
type
<string> A single <PerformanceEntry> type. Must not be given ifentryTypes
is already specified. -
entryTypes
<string[]> 标识监视器感兴趣的 <PerformanceEntry> 实例类型的字符串数组。如果未提供,将抛出错误。¥
entryTypes
<string[]> An array of strings identifying the types of <PerformanceEntry> instances the observer is interested in. If not provided an error will be thrown. -
buffered
<boolean> 如果为 true,则使用列表全局PerformanceEntry
缓冲条目调用监视器回调。如果为 false,则只有在该时间点之后创建的PerformanceEntry
被发送到监视器回调。默认值:false
。¥
buffered
<boolean> If true, the observer callback is called with a list globalPerformanceEntry
buffered entries. If false, onlyPerformanceEntry
s created after the time point are sent to the observer callback. Default:false
.
-
为 <PerformanceObserver> 实例订阅由 options.entryTypes
或 options.type
标识的新 <PerformanceEntry> 实例的通知:
¥Subscribes the <PerformanceObserver> instance to notifications of new
<PerformanceEntry> instances identified either by options.entryTypes
or options.type
:
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}`);
类: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()
#
-
¥Returns: <PerformanceEntry[]>
返回 PerformanceEntry
对象的列表,按照相对于 performanceEntry.startTime
的时间顺序排列。
¥Returns a list of PerformanceEntry
objects in chronological order
with respect to performanceEntry.startTime
.
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> -
¥Returns: <PerformanceEntry[]>
返回按时间顺序的 PerformanceEntry
对象列表,其中 performanceEntry.startTime
的 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
.
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> -
¥Returns: <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
.
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
。¥
lowest
<number> | <bigint> The lowest discernible value. Must be an integer value greater than 0. Default:1
. -
highest
<number> | <bigint> 最高可记录值。必须是等于或大于lowest
两倍的整数值。默认值:Number.MAX_SAFE_INTEGER
。¥
highest
<number> | <bigint> The highest recordable value. Must be an integer value that is equal to or greater than two timeslowest
. Default:Number.MAX_SAFE_INTEGER
. -
figures
<number> 精度位数。必须是1
和5
之间的数字。默认值:3
。¥
figures
<number> The number of accuracy digits. Must be a number between1
and5
. Default:3
.
-
-
¥Returns: <RecordableHistogram>
¥Returns a <RecordableHistogram>.
perf_hooks.monitorEventLoopDelay([options])
#
-
options
<Object> -
¥Returns: <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.
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
#
直方图记录的样本数。
¥The number of samples recorded by the histogram.
histogram.countBigInt
#
直方图记录的样本数。
¥The number of samples recorded by the histogram.
histogram.exceeds
#
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
¥The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
histogram.exceedsBigInt
#
事件循环延迟超过最大 1 小时事件循环延迟阈值的次数。
¥The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.
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.min
#
记录的事件循环延迟的最小值。
¥The minimum recorded event loop delay.
histogram.minBigInt
#
记录的事件循环延迟的最小值。
¥The minimum recorded event loop delay.
histogram.percentile(percentile)
#
-
percentile
<number> 范围 (0, 100] 内的百分位值。¥
percentile
<number> A percentile value in the range (0, 100]. -
返回:<number>
¥Returns: <number>
返回给定的百分位数的值。
¥Returns the value at the given percentile.
histogram.percentileBigInt(percentile)
#
-
percentile
<number> 范围 (0, 100] 内的百分位值。¥
percentile
<number> A percentile value in the range (0, 100]. -
返回:<bigint>
¥Returns: <bigint>
返回给定的百分位数的值。
¥Returns the value at the given percentile.
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.reset()
#
重置收集的直方图数据。
¥Resets the collected histogram data.
histogram.stddev
#
记录的事件循环延迟的标准偏差。
¥The standard deviation of the recorded event loop delays.
类:IntervalHistogram extends Histogram
#
¥Class: IntervalHistogram extends Histogram
在给定的时间间隔内定期更新的 Histogram
。
¥A Histogram
that is periodically updated on a given interval.
histogram.disable()
#
禁用更新间隔定时器。如果定时器已停止,则返回 true
;如果定时器已经停止,则返回 false
。
¥Disables the update interval timer. Returns true
if the timer was
stopped, false
if it was already stopped.
histogram.enable()
#
启用更新间隔定时器。如果定时器已启动,则返回 true
;如果已经启动,则返回 false
。
¥Enables the update interval timer. Returns true
if the timer was
started, false
if it was already started.
克隆 IntervalHistogram
#
¥Cloning an IntervalHistogram
可以通过 <MessagePort> 克隆 <IntervalHistogram> 实例。在接收端,直方图被克隆为不实现 enable()
和 disable()
方法的普通 <Histogram> 对象。
¥<IntervalHistogram> instances can be cloned via <MessagePort>. On the receiving
end, the histogram is cloned as a plain <Histogram> object that does not
implement the enable()
and disable()
methods.
类:RecordableHistogram extends 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
以下示例使用 异步钩子 和性能 API 来测量超时操作的实际持续时间(包括执行回调所花费的时间量)。
¥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).
'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'], buffered: true });
setTimeout(() => {}, 1000);
测量加载依赖需要多长时间#
¥Measuring how long it takes to load dependencies
以下示例测量加载依赖的 require()
操作的持续时间:
¥The following example measures the duration of require()
operations to load
dependencies:
'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'], buffered: true });
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:
'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
'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
'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');