{ "type": "module", "source": "doc/api/perf_hooks.md", "modules": [ { "textRaw": "Performance measurement APIs", "name": "performance_measurement_apis", "introduced_in": "v8.5.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/perf_hooks.js
\nThis module provides an implementation of a subset of the W3C\nWeb Performance APIs as well as additional APIs for\nNode.js-specific performance measurements.
\nNode.js supports the following Web Performance APIs:
\n\nconst { PerformanceObserver, performance } = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n console.log(items.getEntries()[0].duration);\n performance.clearMarks();\n});\nobs.observe({ type: 'measure' });\nperformance.measure('Start to Now');\n\nperformance.mark('A');\ndoSomeLongRunningProcess(() => {\n performance.measure('A to Now', 'A');\n\n performance.mark('B');\n performance.measure('A to B', 'A', 'B');\n});\n
",
"properties": [
{
"textRaw": "`perf_hooks.performance`",
"name": "performance",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"desc": "An object that can be used to collect performance metrics from the current\nNode.js instance. It is similar to window.performance
in browsers.
If name
is not provided, removes all PerformanceMark
objects from the\nPerformance Timeline. If name
is provided, removes only the named mark.
If name
is not provided, removes all PerformanceMeasure
objects from the\nPerformance Timeline. If name
is provided, removes only the named measure.
If name
is not provided, removes all PerformanceResourceTiming
objects from\nthe Resource Timeline. If name
is provided, removes only the named resource.
The eventLoopUtilization()
method returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization
value is the calculated\nEvent Loop Utilization (ELU).
If bootstrapping has not yet finished on the main thread the properties have\nthe value of 0
. The ELU is immediately available on Worker threads since\nbootstrap happens within the event loop.
Both utilization1
and utilization2
are optional parameters.
If utilization1
is passed, then the delta between the current call's active
\nand idle
times, as well as the corresponding utilization
value are\ncalculated and returned (similar to process.hrtime()
).
If utilization1
and utilization2
are both passed, then the delta is\ncalculated between the two arguments. This is a convenience option because,\nunlike process.hrtime()
, calculating the ELU is more complex than a\nsingle subtraction.
ELU is similar to CPU utilization, except that it only measures event loop\nstatistics and not CPU usage. It represents the percentage of time the event\nloop has spent outside the event loop's event provider (e.g. epoll_wait
).\nNo other CPU idle time is taken into consideration. The following is an example\nof how a mostly idle process will have a high ELU.
'use strict';\nconst { eventLoopUtilization } = require('node:perf_hooks').performance;\nconst { spawnSync } = require('node:child_process');\n\nsetImmediate(() => {\n const elu = eventLoopUtilization();\n spawnSync('sleep', ['5']);\n console.log(eventLoopUtilization(elu).utilization);\n});\n
\nAlthough the CPU is mostly idle while running this script, the value of\nutilization
is 1
. This is because the call to\nchild_process.spawnSync()
blocks the event loop from proceeding.
Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization()
will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.
Returns a list of PerformanceEntry
objects in chronological order with\nrespect to performanceEntry.startTime
. If you are only interested in\nperformance entries of certain types or that have certain names, see\nperformance.getEntriesByType()
and performance.getEntriesByName()
.
Returns a list of PerformanceEntry
objects in chronological order\nwith respect to performanceEntry.startTime
whose performanceEntry.name
is\nequal to name
, and optionally, whose performanceEntry.entryType
is equal to\ntype
.
Returns a list of PerformanceEntry
objects in chronological order\nwith respect to performanceEntry.startTime
whose performanceEntry.entryType
\nis equal to type
.
Creates a new PerformanceMark
entry in the Performance Timeline. A\nPerformanceMark
is a subclass of PerformanceEntry
whose\nperformanceEntry.entryType
is always 'mark'
, and whose\nperformanceEntry.duration
is always 0
. Performance marks are used\nto mark specific significant moments in the Performance Timeline.
The created PerformanceMark
entry is put in the global Performance Timeline\nand can be queried with performance.getEntries
,\nperformance.getEntriesByName
, and performance.getEntriesByType
. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearMarks
.
This property is an extension by Node.js. It is not available in Web browsers.
\nCreates a new PerformanceResourceTiming
entry in the Resource Timeline. A\nPerformanceResourceTiming
is a subclass of PerformanceEntry
whose\nperformanceEntry.entryType
is always 'resource'
. Performance resources\nare used to mark moments in the Resource Timeline.
The created PerformanceMark
entry is put in the global Resource Timeline\nand can be queried with performance.getEntries
,\nperformance.getEntriesByName
, and performance.getEntriesByType
. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearResourceTimings
.
Creates a new PerformanceMeasure
entry in the Performance Timeline. A\nPerformanceMeasure
is a subclass of PerformanceEntry
whose\nperformanceEntry.entryType
is always 'measure'
, and whose\nperformanceEntry.duration
measures the number of milliseconds elapsed since\nstartMark
and endMark
.
The startMark
argument may identify any existing PerformanceMark
in the\nPerformance Timeline, or may identify any of the timestamp properties\nprovided by the PerformanceNodeTiming
class. If the named startMark
does\nnot exist, an error is thrown.
The optional endMark
argument must identify any existing PerformanceMark
\nin the Performance Timeline or any of the timestamp properties provided by the\nPerformanceNodeTiming
class. endMark
will be performance.now()
\nif no parameter is passed, otherwise if the named endMark
does not exist, an\nerror will be thrown.
The created PerformanceMeasure
entry is put in the global Performance Timeline\nand can be queried with performance.getEntries
,\nperformance.getEntriesByName
, and performance.getEntriesByType
. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearMeasures
.
Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node
process.
Sets the global performance resource timing buffer size to the specified number\nof \"resource\" type performance entry objects.
\nBy default the max buffer size is set to 250.
" }, { "textRaw": "`performance.timerify(fn[, options])`", "type": "method", "name": "timerify", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37475", "description": "Added the histogram option." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Re-implemented to use pure-JavaScript and the ability to time async functions." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function}", "name": "fn", "type": "Function" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`histogram` {RecordableHistogram} A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds.", "name": "histogram", "type": "RecordableHistogram", "desc": "A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds." } ] } ] } ], "desc": "This property is an extension by Node.js. It is not available in Web browsers.
\nWraps a function within a new function that measures the running time of the\nwrapped function. A PerformanceObserver
must be subscribed to the 'function'
\nevent type in order for the timing details to be accessed.
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nfunction someFunction() {\n console.log('hello world');\n}\n\nconst wrapped = performance.timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n console.log(list.getEntries()[0].duration);\n\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n
\nIf the wrapped function returns a promise, a finally handler will be attached\nto the promise and the duration will be reported once the finally handler is\ninvoked.
" }, { "textRaw": "`performance.toJSON()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v16.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "An object which is JSON representation of the performance
object. It\nis similar to window.performance.toJSON
in browsers.
The 'resourcetimingbufferfull'
event is fired when the global performance\nresource timing buffer is full. Adjust resource timing buffer size with\nperformance.setResourceTimingBufferSize()
or clear the buffer with\nperformance.clearResourceTimings()
in the event listener to allow\nmore entries to be added to the performance timeline buffer.
This property is an extension by Node.js. It is not available in Web browsers.
\nAn instance of the PerformanceNodeTiming
class that provides performance\nmetrics for specific Node.js operational milestones.
The timeOrigin
specifies the high resolution millisecond timestamp at\nwhich the current node
process began, measured in Unix time.
Additional detail specific to the entryType
.
The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.
" }, { "textRaw": "`entryType` {string}", "type": "string", "name": "entryType", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The type of the performance entry. It may be one of:
\n'node'
(Node.js only)'mark'
(available on the Web)'measure'
(available on the Web)'gc'
(Node.js only)'function'
(Node.js only)'http2'
(Node.js only)'http'
(Node.js only)This property is an extension by Node.js. It is not available in Web browsers.
\nWhen performanceEntry.entryType
is equal to 'gc'
, the performance.flags
\nproperty contains additional information about garbage collection operation.\nThe 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
The name of the performance entry.
" }, { "textRaw": "`kind` {number}", "type": "number", "name": "kind", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Runtime deprecated. Now moved to the detail property when entryType is 'gc'." } ] }, "desc": "This property is an extension by Node.js. It is not available in Web browsers.
\nWhen performanceEntry.entryType
is equal to 'gc'
, the performance.kind
\nproperty identifies the type of garbage collection operation that occurred.\nThe 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
The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.
" } ], "modules": [ { "textRaw": "Garbage Collection ('gc') Details", "name": "garbage_collection_('gc')_details", "desc": "When performanceEntry.type
is equal to 'gc'
, the performanceEntry.detail
\nproperty will be an <Object> with two properties:
kind
<number> One of:\nperf_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> One of:\nperf_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
When performanceEntry.type
is equal to 'http'
, the performanceEntry.detail
\nproperty will be an <Object> containing additional information.
If performanceEntry.name
is equal to HttpClient
, the detail
\nwill contain the following properties: req
, res
. And the req
property\nwill be an <Object> containing method
, url
, headers
, the res
property\nwill be an <Object> containing statusCode
, statusMessage
, headers
.
If performanceEntry.name
is equal to HttpRequest
, the detail
\nwill contain the following properties: req
, res
. And the req
property\nwill be an <Object> containing method
, url
, headers
, the res
property\nwill be an <Object> containing statusCode
, statusMessage
, headers
.
This could add additional memory overhead and should only be used for\ndiagnostic purposes, not left turned on in production by default.
", "type": "module", "displayName": "HTTP ('http') Details" }, { "textRaw": "HTTP/2 ('http2') Details", "name": "http/2_('http2')_details", "desc": "When performanceEntry.type
is equal to 'http2'
, the\nperformanceEntry.detail
property will be an <Object> containing\nadditional performance information.
If performanceEntry.name
is equal to Http2Stream
, the detail
\nwill contain the following properties:
bytesRead
<number> The number of DATA
frame bytes received for this\nHttp2Stream
.bytesWritten
<number> The number of DATA
frame bytes sent for this\nHttp2Stream
.id
<number> The identifier of the associated Http2Stream
timeToFirstByte
<number> The number of milliseconds elapsed between the\nPerformanceEntry
startTime
and the reception of the first DATA
frame.timeToFirstByteSent
<number> The number of milliseconds elapsed between\nthe PerformanceEntry
startTime
and sending of the first DATA
frame.timeToFirstHeader
<number> The number of milliseconds elapsed between the\nPerformanceEntry
startTime
and the reception of the first header.If performanceEntry.name
is equal to Http2Session
, the detail
will\ncontain the following properties:
bytesRead
<number> The number of bytes received for this Http2Session
.bytesWritten
<number> The number of bytes sent for this Http2Session
.framesReceived
<number> The number of HTTP/2 frames received by the\nHttp2Session
.framesSent
<number> The number of HTTP/2 frames sent by the Http2Session
.maxConcurrentStreams
<number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session
.pingRTT
<number> The number of milliseconds elapsed since the transmission\nof a PING
frame and the reception of its acknowledgment. Only present if\na PING
frame has been sent on the Http2Session
.streamAverageDuration
<number> The average duration (in milliseconds) for\nall Http2Stream
instances.streamCount
<number> The number of Http2Stream
instances processed by\nthe Http2Session
.type
<string> Either 'server'
or 'client'
to identify the type of\nHttp2Session
.When performanceEntry.type
is equal to 'function'
, the\nperformanceEntry.detail
property will be an <Array> listing\nthe input arguments to the timed function.
When performanceEntry.type
is equal to 'net'
, the\nperformanceEntry.detail
property will be an <Object> containing\nadditional information.
If performanceEntry.name
is equal to connect
, the detail
\nwill contain the following properties: host
, port
.
When performanceEntry.type
is equal to 'dns'
, the\nperformanceEntry.detail
property will be an <Object> containing\nadditional information.
If performanceEntry.name
is equal to lookup
, the detail
\nwill contain the following properties: hostname
, family
, hints
, verbatim
,\naddresses
.
If performanceEntry.name
is equal to lookupService
, the detail
will\ncontain the following properties: host
, port
, hostname
, service
.
If performanceEntry.name
is equal to queryxxx
or getHostByAddr
, the detail
will\ncontain the following properties: host
, ttl
, result
. The value of result
is\nsame as the result of queryxxx
or getHostByAddr
.
This property is an extension by Node.js. It is not available in Web browsers.
\nProvides timing details for Node.js itself. The constructor of this class\nis not exposed to users.
", "properties": [ { "textRaw": "`bootstrapComplete` {number}", "type": "number", "name": "bootstrapComplete", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js process\ncompleted bootstrapping. If bootstrapping has not yet finished, the property\nhas the value of -1.
" }, { "textRaw": "`environment` {number}", "type": "number", "name": "environment", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.
" }, { "textRaw": "`idleTime` {number}", "type": "number", "name": "idleTime", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp of the amount of time the event loop\nhas been idle within the event loop's event provider (e.g. epoll_wait
). This\ndoes not take CPU usage into consideration. If the event loop has not yet\nstarted (e.g., in the first tick of the main script), the property has the\nvalue of 0.
The high resolution millisecond timestamp at which the Node.js event loop\nexited. If the event loop has not yet exited, the property has the value of -1.\nIt can only have a value of not -1 in a handler of the 'exit'
event.
The high resolution millisecond timestamp at which the Node.js event loop\nstarted. If the event loop has not yet started (e.g., in the first tick of the\nmain script), the property has the value of -1.
" }, { "textRaw": "`nodeStart` {number}", "type": "number", "name": "nodeStart", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js process was\ninitialized.
" }, { "textRaw": "`v8Start` {number}", "type": "number", "name": "v8Start", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the V8 platform was\ninitialized.
" } ] }, { "textRaw": "Class: `PerformanceResourceTiming`", "type": "class", "name": "PerformanceResourceTiming", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "Provides detailed network timing data regarding the loading of an application's\nresources.
\nThe constructor of this class is not exposed to users directly.
", "properties": [ { "textRaw": "`workerStart` {number}", "type": "number", "name": "workerStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at immediately before dispatching\nthe fetch
request. If the resource is not intercepted by a worker the property\nwill always return 0.
The high resolution millisecond timestamp that represents the start time\nof the fetch which initiates the redirect.
" }, { "textRaw": "`redirectEnd` {number}", "type": "number", "name": "redirectEnd", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp that will be created immediately after\nreceiving the last byte of the response of the last redirect.
" }, { "textRaw": "`fetchStart` {number}", "type": "number", "name": "fetchStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp immediately before the Node.js starts\nto fetch the resource.
" }, { "textRaw": "`domainLookupStart` {number}", "type": "number", "name": "domainLookupStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp immediately before the Node.js starts\nthe domain name lookup for the resource.
" }, { "textRaw": "`domainLookupEnd` {number}", "type": "number", "name": "domainLookupEnd", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter the Node.js finished the domain name lookup for the resource.
" }, { "textRaw": "`connectStart` {number}", "type": "number", "name": "connectStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts to establish the connection to the server to retrieve\nthe resource.
" }, { "textRaw": "`connectEnd` {number}", "type": "number", "name": "connectEnd", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter Node.js finishes establishing the connection to the server to retrieve\nthe resource.
" }, { "textRaw": "`secureConnectionStart` {number}", "type": "number", "name": "secureConnectionStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts the handshake process to secure the current connection.
" }, { "textRaw": "`requestStart` {number}", "type": "number", "name": "requestStart", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js receives the first byte of the response from the server.
" }, { "textRaw": "`responseEnd` {number}", "type": "number", "name": "responseEnd", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter Node.js receives the last byte of the resource or immediately before\nthe transport connection is closed, whichever comes first.
" }, { "textRaw": "`transferSize` {number}", "type": "number", "name": "transferSize", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "A number representing the size (in octets) of the fetched resource. The size\nincludes the response header fields plus the response payload body.
" }, { "textRaw": "`encodedBodySize` {number}", "type": "number", "name": "encodedBodySize", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "A number representing the size (in octets) received from the fetch\n(HTTP or cache), of the payload body, before removing any applied\ncontent-codings.
" }, { "textRaw": "`decodedBodySize` {number}", "type": "number", "name": "decodedBodySize", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "desc": "A number representing the size (in octets) received from the fetch\n(HTTP or cache), of the message body, after removing any applied\ncontent-codings.
" } ], "methods": [ { "textRaw": "`performanceResourceTiming.toJSON()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v18.2.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Returns a object
that is the JSON representation of the\nPerformanceResourceTiming
object
Get supported types.
" } ], "methods": [ { "textRaw": "`performanceObserver.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Disconnects the PerformanceObserver
instance from all notifications.
Subscribes the <PerformanceObserver> instance to notifications of new\n<PerformanceEntry> instances identified either by options.entryTypes
\nor options.type
:
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n // Called once asynchronously. `list` contains three items.\n});\nobs.observe({ type: 'mark' });\n\nfor (let n = 0; n < 3; n++)\n performance.mark(`test${n}`);\n
"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`list` {PerformanceObserverEntryList}",
"name": "list",
"type": "PerformanceObserverEntryList"
},
{
"textRaw": "`observer` {PerformanceObserver}",
"name": "observer",
"type": "PerformanceObserver"
}
]
}
],
"desc": "PerformanceObserver
objects provide notifications when new\nPerformanceEntry
instances have been added to the Performance Timeline.
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries());\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n
\nBecause PerformanceObserver
instances introduce their own additional\nperformance overhead, instances should not be left subscribed to notifications\nindefinitely. Users should disconnect observers as soon as they are no\nlonger needed.
The callback
is invoked when a PerformanceObserver
is\nnotified about new PerformanceEntry
instances. The callback receives a\nPerformanceObserverEntryList
instance and a reference to the\nPerformanceObserver
.
The PerformanceObserverEntryList
class is used to provide access to the\nPerformanceEntry
instances passed to a PerformanceObserver
.\nThe constructor of this class is not exposed to users.
Returns a list of PerformanceEntry
objects in chronological order\nwith respect to performanceEntry.startTime
.
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntries());\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 81.465639,\n * duration: 0\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 81.860064,\n * duration: 0\n * }\n * ]\n */\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n
"
},
{
"textRaw": "`performanceObserverEntryList.getEntriesByName(name[, type])`",
"type": "method",
"name": "getEntriesByName",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {PerformanceEntry\\[]}",
"name": "return",
"type": "PerformanceEntry\\[]"
},
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`type` {string}",
"name": "type",
"type": "string"
}
]
}
],
"desc": "Returns a list of PerformanceEntry
objects in chronological order\nwith respect to performanceEntry.startTime
whose performanceEntry.name
is\nequal to name
, and optionally, whose performanceEntry.entryType
is equal to\ntype
.
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByName('meow'));\n /**\n * [\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 98.545991,\n * duration: 0\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('nope')); // []\n\n console.log(perfObserverList.getEntriesByName('test', 'mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 63.518931,\n * duration: 0\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('test', 'measure')); // []\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark', 'measure'] });\n\nperformance.mark('test');\nperformance.mark('meow');\n
"
},
{
"textRaw": "`performanceObserverEntryList.getEntriesByType(type)`",
"type": "method",
"name": "getEntriesByType",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {PerformanceEntry\\[]}",
"name": "return",
"type": "PerformanceEntry\\[]"
},
"params": [
{
"textRaw": "`type` {string}",
"name": "type",
"type": "string"
}
]
}
],
"desc": "Returns a list of PerformanceEntry
objects in chronological order\nwith respect to performanceEntry.startTime
whose performanceEntry.entryType
\nis equal to type
.
const {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByType('mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 55.897834,\n * duration: 0\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 56.350146,\n * duration: 0\n * }\n * ]\n */\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n
"
}
]
},
{
"textRaw": "Class: `Histogram`",
"type": "class",
"name": "Histogram",
"meta": {
"added": [
"v11.10.0"
],
"changes": []
},
"properties": [
{
"textRaw": "`count` {number}",
"type": "number",
"name": "count",
"meta": {
"added": [
"v17.4.0",
"v16.14.0"
],
"changes": []
},
"desc": "The number of samples recorded by the histogram.
" }, { "textRaw": "`countBigInt` {bigint}", "type": "bigint", "name": "countBigInt", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The number of samples recorded by the histogram.
" }, { "textRaw": "`exceeds` {number}", "type": "number", "name": "exceeds", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.
" }, { "textRaw": "`exceedsBigInt` {bigint}", "type": "bigint", "name": "exceedsBigInt", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.
" }, { "textRaw": "`max` {number}", "type": "number", "name": "max", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The maximum recorded event loop delay.
" }, { "textRaw": "`maxBigInt` {bigint}", "type": "bigint", "name": "maxBigInt", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The maximum recorded event loop delay.
" }, { "textRaw": "`mean` {number}", "type": "number", "name": "mean", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The mean of the recorded event loop delays.
" }, { "textRaw": "`min` {number}", "type": "number", "name": "min", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The minimum recorded event loop delay.
" }, { "textRaw": "`minBigInt` {bigint}", "type": "bigint", "name": "minBigInt", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The minimum recorded event loop delay.
" }, { "textRaw": "`percentiles` {Map}", "type": "Map", "name": "percentiles", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "Returns a Map
object detailing the accumulated percentile distribution.
Returns a Map
object detailing the accumulated percentile distribution.
The standard deviation of the recorded event loop delays.
" } ], "methods": [ { "textRaw": "`histogram.percentile(percentile)`", "type": "method", "name": "percentile", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`percentile` {number} A percentile value in the range (0, 100].", "name": "percentile", "type": "number", "desc": "A percentile value in the range (0, 100]." } ] } ], "desc": "Returns the value at the given percentile.
" }, { "textRaw": "`histogram.percentileBigInt(percentile)`", "type": "method", "name": "percentileBigInt", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "params": [ { "textRaw": "`percentile` {number} A percentile value in the range (0, 100].", "name": "percentile", "type": "number", "desc": "A percentile value in the range (0, 100]." } ] } ], "desc": "Returns the value at the given percentile.
" }, { "textRaw": "`histogram.reset()`", "type": "method", "name": "reset", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Resets the collected histogram data.
" } ] }, { "textRaw": "Class: `IntervalHistogram extends Histogram`", "type": "class", "name": "IntervalHistogram", "desc": "A Histogram
that is periodically updated on a given interval.
Disables the update interval timer. Returns true
if the timer was\nstopped, false
if it was already stopped.
Enables the update interval timer. Returns true
if the timer was\nstarted, false
if it was already started.
<IntervalHistogram> instances can be cloned via <MessagePort>. On the receiving\nend, the histogram is cloned as a plain <Histogram> object that does not\nimplement the enable()
and disable()
methods.
Adds the values from other
to this histogram.
Calculates the amount of time (in nanoseconds) that has passed since the\nprevious call to recordDelta()
and records that amount in the histogram.
The following example uses the Async Hooks and Performance APIs to measure\nthe actual duration of a Timeout operation (including the amount of time it took\nto execute the callback).
\n'use strict';\nconst async_hooks = require('node:async_hooks');\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst set = new Set();\nconst hook = async_hooks.createHook({\n init(id, type) {\n if (type === 'Timeout') {\n performance.mark(`Timeout-${id}-Init`);\n set.add(id);\n }\n },\n destroy(id) {\n if (set.has(id)) {\n set.delete(id);\n performance.mark(`Timeout-${id}-Destroy`);\n performance.measure(`Timeout-${id}`,\n `Timeout-${id}-Init`,\n `Timeout-${id}-Destroy`);\n }\n },\n});\nhook.enable();\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries()[0]);\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'], buffered: true });\n\nsetTimeout(() => {}, 1000);\n
",
"type": "module",
"displayName": "Measuring the duration of async operations"
},
{
"textRaw": "Measuring how long it takes to load dependencies",
"name": "measuring_how_long_it_takes_to_load_dependencies",
"desc": "The following example measures the duration of require()
operations to load\ndependencies:
'use strict';\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\nconst mod = require('node:module');\n\n// Monkey patch the require function\nmod.Module.prototype.require =\n performance.timerify(mod.Module.prototype.require);\nrequire = performance.timerify(require);\n\n// Activate the observer\nconst obs = new PerformanceObserver((list) => {\n const entries = list.getEntries();\n entries.forEach((entry) => {\n console.log(`require('${entry[0]}')`, entry.duration);\n });\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'], buffered: true });\n\nrequire('some-module');\n
",
"type": "module",
"displayName": "Measuring how long it takes to load dependencies"
},
{
"textRaw": "Measuring how long one HTTP round-trip takes",
"name": "measuring_how_long_one_http_round-trip_takes",
"desc": "The following example is used to trace the time spent by HTTP client\n(OutgoingMessage
) and HTTP request (IncomingMessage
). For HTTP client,\nit means the time interval between starting the request and receiving the\nresponse, and for HTTP request, it means the time interval between receiving\nthe request and sending the response:
'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst http = require('node:http');\n\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\n\nobs.observe({ entryTypes: ['http'] });\n\nconst PORT = 8080;\n\nhttp.createServer((req, res) => {\n res.end('ok');\n}).listen(PORT, () => {\n http.get(`http://127.0.0.1:${PORT}`);\n});\n
",
"type": "module",
"displayName": "Measuring how long one HTTP round-trip takes"
},
{
"textRaw": "Measuring how long the `net.connect` (only for TCP) takes when the connection is successful",
"name": "measuring_how_long_the_`net.connect`_(only_for_tcp)_takes_when_the_connection_is_successful",
"desc": "'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst net = require('node:net');\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['net'] });\nconst PORT = 8080;\nnet.createServer((socket) => {\n socket.destroy();\n}).listen(PORT, () => {\n net.connect(PORT);\n});\n
",
"type": "module",
"displayName": "Measuring how long the `net.connect` (only for TCP) takes when the connection is successful"
},
{
"textRaw": "Measuring how long the DNS takes when the request is successful",
"name": "measuring_how_long_the_dns_takes_when_the_request_is_successful",
"desc": "'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst dns = require('node:dns');\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['dns'] });\ndns.lookup('localhost', () => {});\ndns.promises.resolve('localhost');\n
",
"type": "module",
"displayName": "Measuring how long the DNS takes when the request is successful"
}
]
}
],
"methods": [
{
"textRaw": "`perf_hooks.createHistogram([options])`",
"type": "method",
"name": "createHistogram",
"meta": {
"added": [
"v15.9.0",
"v14.18.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns {RecordableHistogram}",
"name": "return",
"type": "RecordableHistogram"
},
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`lowest` {number|bigint} The lowest discernible value. Must be an integer value greater than 0. **Default:** `1`.",
"name": "lowest",
"type": "number|bigint",
"default": "`1`",
"desc": "The lowest discernible value. Must be an integer value greater than 0."
},
{
"textRaw": "`highest` {number|bigint} The highest recordable value. Must be an integer value that is equal to or greater than two times `lowest`. **Default:** `Number.MAX_SAFE_INTEGER`.",
"name": "highest",
"type": "number|bigint",
"default": "`Number.MAX_SAFE_INTEGER`",
"desc": "The highest recordable value. Must be an integer value that is equal to or greater than two times `lowest`."
},
{
"textRaw": "`figures` {number} The number of accuracy digits. Must be a number between `1` and `5`. **Default:** `3`.",
"name": "figures",
"type": "number",
"default": "`3`",
"desc": "The number of accuracy digits. Must be a number between `1` and `5`."
}
]
}
]
}
],
"desc": "Returns a <RecordableHistogram>.
" }, { "textRaw": "`perf_hooks.monitorEventLoopDelay([options])`", "type": "method", "name": "monitorEventLoopDelay", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {IntervalHistogram}", "name": "return", "type": "IntervalHistogram" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`resolution` {number} The sampling rate in milliseconds. Must be greater than zero. **Default:** `10`.", "name": "resolution", "type": "number", "default": "`10`", "desc": "The sampling rate in milliseconds. Must be greater than zero." } ] } ] } ], "desc": "This property is an extension by Node.js. It is not available in Web browsers.
\nCreates an IntervalHistogram
object that samples and reports the event loop\ndelay over time. The delays will be reported in nanoseconds.
Using a timer to detect approximate event loop delay works because the\nexecution of timers is tied specifically to the lifecycle of the libuv\nevent loop. That is, a delay in the loop will cause a delay in the execution\nof the timer, and those delays are specifically what this API is intended to\ndetect.
\nconst { monitorEventLoopDelay } = require('node:perf_hooks');\nconst h = monitorEventLoopDelay({ resolution: 20 });\nh.enable();\n// Do something.\nh.disable();\nconsole.log(h.min);\nconsole.log(h.max);\nconsole.log(h.mean);\nconsole.log(h.stddev);\nconsole.log(h.percentiles);\nconsole.log(h.percentile(50));\nconsole.log(h.percentile(99));\n
"
}
],
"type": "module",
"displayName": "Performance measurement APIs"
}
]
}