Source Code: lib/perf_hooks.js
This module provides an implementation of a subset of the W3C\nWeb Performance APIs as well as additional APIs for\nNode.js-specific performance measurements.
Node.js supports the following Web Performance APIs:
const { 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
An object that can be used to collect performance metrics from the current\nNode.js instance. It is similar to window.performance in browsers.
window.performance
If name is not provided, removes all PerformanceMark objects from the\nPerformance Timeline. If name is provided, removes only the named mark.
name
PerformanceMark
If name is not provided, removes all PerformanceMeasure objects from the\nPerformance Timeline. If name is provided, removes only the named measure.
PerformanceMeasure
If name is not provided, removes all PerformanceResourceTiming objects from\nthe Resource Timeline. If name is provided, removes only the named resource.
PerformanceResourceTiming
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).
eventLoopUtilization()
utilization
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.
0
Both utilization1 and utilization2 are optional parameters.
utilization1
utilization2
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()).
active
idle
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.
epoll_wait
'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
Although 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.
1
child_process.spawnSync()
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().
PerformanceEntry
performanceEntry.startTime
performance.getEntriesByType()
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.
performanceEntry.name
performanceEntry.entryType
type
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.
'mark'
performanceEntry.duration
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.
performance.getEntries
performance.getEntriesByName
performance.getEntriesByType
performance.clearMarks
This property is an extension by Node.js. It is not available in Web browsers.
Creates 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.
'resource'
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.
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.
'measure'
startMark
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.
PerformanceNodeTiming
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.
performance.now()
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.
performance.clearMeasures
Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.
node
Wraps 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.
PerformanceObserver
'function'
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
If 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.
An object which is JSON representation of the performance object. It\nis similar to window.performance.toJSON in browsers.
performance
window.performance.toJSON
An 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.
timeOrigin
Additional detail specific to the entryType.
entryType
The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.
The type of the performance entry. It may be one of:
'node'
'gc'
'http2'
'http'
When performanceEntry.entryType is equal to 'gc', the performance.flags\nproperty contains additional information about garbage collection operation.\nThe value may be one of:
performance.flags
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.
When 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:
performance.kind
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.
When performanceEntry.type is equal to 'gc', the performanceEntry.detail\nproperty will be an <Object> with two properties:
performanceEntry.type
performanceEntry.detail
kind
flags
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.
HttpClient
detail
req
res
method
url
headers
statusCode
statusMessage
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.
HttpRequest
This could add additional memory overhead and should only be used for\ndiagnostic purposes, not left turned on in production by default.
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:
Http2Stream
bytesRead
DATA
bytesWritten
id
timeToFirstByte
startTime
timeToFirstByteSent
timeToFirstHeader
If performanceEntry.name is equal to Http2Session, the detail will\ncontain the following properties:
Http2Session
framesReceived
framesSent
maxConcurrentStreams
pingRTT
PING
streamAverageDuration
streamCount
'server'
'client'
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.
'net'
If performanceEntry.name is equal to connect, the detail\nwill contain the following properties: host, port.
connect
host
port
When performanceEntry.type is equal to 'dns', the\nperformanceEntry.detail property will be an <Object> containing\nadditional information.
'dns'
If performanceEntry.name is equal to lookup, the detail\nwill contain the following properties: hostname, family, hints, verbatim,\naddresses.
lookup
hostname
family
hints
verbatim
addresses
If performanceEntry.name is equal to lookupService, the detail will\ncontain the following properties: host, port, hostname, service.
lookupService
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.
queryxxx
getHostByAddr
ttl
result
Provides timing details for Node.js itself. The constructor of this class\nis not exposed to users.
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.
The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.
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.
'exit'
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.
The high resolution millisecond timestamp at which the Node.js process was\ninitialized.
The high resolution millisecond timestamp at which the V8 platform was\ninitialized.
Provides detailed network timing data regarding the loading of an application's\nresources.
The constructor of this class is not exposed to users directly.
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.
fetch
The high resolution millisecond timestamp that represents the start time\nof the fetch which initiates the redirect.
The high resolution millisecond timestamp that will be created immediately after\nreceiving the last byte of the response of the last redirect.
The high resolution millisecond timestamp immediately before the Node.js starts\nto fetch the resource.
The high resolution millisecond timestamp immediately before the Node.js starts\nthe domain name lookup for the resource.
The high resolution millisecond timestamp representing the time immediately\nafter the Node.js finished the domain name lookup for the resource.
The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts to establish the connection to the server to retrieve\nthe resource.
The high resolution millisecond timestamp representing the time immediately\nafter Node.js finishes establishing the connection to the server to retrieve\nthe resource.
The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts the handshake process to secure the current connection.
The high resolution millisecond timestamp representing the time immediately\nbefore Node.js receives the first byte of the response from the server.
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.
A number representing the size (in octets) of the fetched resource. The size\nincludes the response header fields plus the response payload body.
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.
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.
Returns a object that is the JSON representation of the\nPerformanceResourceTiming object
object
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:
options.entryTypes
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
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
Because 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.
callback
PerformanceObserverEntryList
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
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
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
The number of samples recorded by the histogram.
The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.
The maximum recorded event loop delay.
The mean of the recorded event loop delays.
The minimum recorded event loop delay.
Returns a Map object detailing the accumulated percentile distribution.
Map
The standard deviation of the recorded event loop delays.
Returns the value at the given percentile.
Resets the collected histogram data.
A Histogram that is periodically updated on a given interval.
Histogram
Disables the update interval timer. Returns true if the timer was\nstopped, false if it was already stopped.
true
false
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.
enable()
disable()
Adds the values from other to this histogram.
other
Calculates the amount of time (in nanoseconds) that has passed since the\nprevious call to recordDelta() and records that amount in the histogram.
recordDelta()
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).
'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
The following example measures the duration of require() operations to load\ndependencies:
require()
'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
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:
OutgoingMessage
IncomingMessage
'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
'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
'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
Returns a <RecordableHistogram>.
Creates an IntervalHistogram object that samples and reports the event loop\ndelay over time. The delays will be reported in nanoseconds.
IntervalHistogram
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.
const { 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