{ "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('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n console.log(items.getEntries()[0].duration);\n performance.clearMarks();\n});\nobs.observe({ entryTypes: ['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.
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('perf_hooks').performance;\nconst { spawnSync } = require('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.
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.
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, then startMark is set to timeOrigin by default.
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.
Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.
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('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 obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n"
},
{
"textRaw": "`performance.eventLoopUtilization([util1][,util2])`",
"type": "method",
"name": "eventLoopUtilization",
"meta": {
"added": [
"v12.19.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`idle` {number}",
"name": "idle",
"type": "number"
},
{
"textRaw": "`active` {number}",
"name": "active",
"type": "number"
},
{
"textRaw": "`utilization` {number}",
"name": "utilization",
"type": "number"
}
]
},
"params": [
{
"textRaw": "`util1` {Object} The result of a previous call to `eventLoopUtilization()`",
"name": "util1",
"type": "Object",
"desc": "The result of a previous call to `eventLoopUtilization()`"
},
{
"textRaw": "`util2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `util1`",
"name": "util2",
"type": "Object",
"desc": "The result of a previous call to `eventLoopUtilization()` prior to `util1`"
}
]
}
],
"desc": "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, the\nproperties have the value of 0.
util1 and util2 are optional parameters.
If util1 is passed then the delta between the current call's active and\nidle times are calculated and returned (similar to process.hrtime()).\nLikewise the adjusted utilization value is calculated.
If util1 and util2 are both passed then the calculation adjustments are\ndone between the two arguments. This is a convenience option because unlike\nprocess.hrtime() additional work is done to calculate the ELU.
ELU is similar to CPU utilization except that it is calculated using high\nprecision wall-clock time. It represents the percentage of time the event loop\nhas spent outside the event loop's event provider (e.g. epoll_wait). No other\nCPU idle time is taken into consideration. The following is an example of how\na mostly idle process will have a high ELU.
'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('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 child_process.spawnSync()\nblocks 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.
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.
The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.
" }, { "textRaw": "`name` {string}", "type": "string", "name": "name", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The name of the performance entry.
" }, { "textRaw": "`startTime` {number}", "type": "number", "name": "startTime", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.
" }, { "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.kind\nproperty identifies the type of garbage collection operation that occurred.\nThe value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCBThis 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_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLEThis 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": "`loopExit` {number}", "type": "number", "name": "loopExit", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "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": "`idleTime` {number}", "type": "number", "name": "idleTime", "meta": { "added": [ "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.
Disconnects the PerformanceObserver instance from all notifications.
Subscribes the PerformanceObserver instance to notifications of new\nPerformanceEntry instances identified by options.entryTypes.
When options.buffered is false, the callback will be invoked once for\nevery PerformanceEntry instance:
const {\n performance,\n PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n // Called three times synchronously. `list` contains one item.\n});\nobs.observe({ entryTypes: ['mark'] });\n\nfor (let n = 0; n < 3; n++)\n performance.mark(`test${n}`);\n\nconst {\n performance,\n PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n // Called once. `list` contains three items.\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\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('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries());\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.
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.
This property is an extension by Node.js. It is not available in Web browsers.
\nCreates a Histogram object that samples and reports the event loop delay\nover 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('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",
"classes": [
{
"textRaw": "Class: `Histogram`",
"type": "class",
"name": "Histogram",
"meta": {
"added": [
"v11.10.0"
],
"changes": []
},
"desc": "Tracks the event loop delay at a given sampling rate. The constructor of\nthis class not exposed to users.
\nThis property is an extension by Node.js. It is not available in Web browsers.
", "methods": [ { "textRaw": "`histogram.disable()`", "type": "method", "name": "disable", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "Disables the event loop delay sample timer. Returns true if the timer was\nstopped, false if it was already stopped.
Enables the event loop delay sample timer. Returns true if the timer was\nstarted, false if it was already started.
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.
" } ], "properties": [ { "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": "`max` {number}", "type": "number", "name": "max", "meta": { "added": [ "v11.10.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": "`percentiles` {Map}", "type": "Map", "name": "percentiles", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "Returns a Map object detailing the accumulated percentile distribution.
The standard deviation of the recorded event loop delays.
\nThe 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('async_hooks');\nconst {\n performance,\n PerformanceObserver\n} = require('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 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('perf_hooks');\nconst mod = require('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 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"
}
]
}
],
"type": "module",
"displayName": "Performance measurement APIs"
}
]
}