Skip to content

Commit 7d8c1e7

Browse files
mfdebianruyadorno
authored andcommittedJan 5, 2025
doc: add esm examples to node:perf_hooks
PR-URL: #55257 Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent 04d7c7a commit 7d8c1e7

File tree

1 file changed

+328
-14
lines changed

1 file changed

+328
-14
lines changed
 

‎doc/api/perf_hooks.md

+328-14
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,26 @@ Node.js supports the following [Web Performance APIs][]:
1717
* [User Timing][]
1818
* [Resource Timing][]
1919

20-
```js
20+
```mjs
21+
import { performance, PerformanceObserver } from 'node:perf_hooks';
22+
23+
const obs = new PerformanceObserver((items) => {
24+
console.log(items.getEntries()[0].duration);
25+
performance.clearMarks();
26+
});
27+
obs.observe({ type: 'measure' });
28+
performance.measure('Start to Now');
29+
30+
performance.mark('A');
31+
doSomeLongRunningProcess(() => {
32+
performance.measure('A to Now', 'A');
33+
34+
performance.mark('B');
35+
performance.measure('A to B', 'A', 'B');
36+
});
37+
```
38+
39+
```cjs
2140
const { PerformanceObserver, performance } = require('node:perf_hooks');
2241

2342
const obs = new PerformanceObserver((items) => {
@@ -138,7 +157,18 @@ loop has spent outside the event loop's event provider (e.g. `epoll_wait`).
138157
No other CPU idle time is taken into consideration. The following is an example
139158
of how a mostly idle process will have a high ELU.
140159

141-
```js
160+
```mjs
161+
import { eventLoopUtilization } from 'node:perf_hooks';
162+
import { spawnSync } from 'node:child_process';
163+
164+
setImmediate(() => {
165+
const elu = eventLoopUtilization();
166+
spawnSync('sleep', ['5']);
167+
console.log(eventLoopUtilization(elu).utilization);
168+
});
169+
```
170+
171+
```cjs
142172
'use strict';
143173
const { eventLoopUtilization } = require('node:perf_hooks').performance;
144174
const { spawnSync } = require('node:child_process');
@@ -415,7 +445,29 @@ Wraps a function within a new function that measures the running time of the
415445
wrapped function. A `PerformanceObserver` must be subscribed to the `'function'`
416446
event type in order for the timing details to be accessed.
417447

418-
```js
448+
```mjs
449+
import { performance, PerformanceObserver } from 'node:perf_hooks';
450+
451+
function someFunction() {
452+
console.log('hello world');
453+
}
454+
455+
const wrapped = performance.timerify(someFunction);
456+
457+
const obs = new PerformanceObserver((list) => {
458+
console.log(list.getEntries()[0].duration);
459+
460+
performance.clearMarks();
461+
performance.clearMeasures();
462+
obs.disconnect();
463+
});
464+
obs.observe({ entryTypes: ['function'] });
465+
466+
// A performance timeline entry will be created
467+
wrapped();
468+
```
469+
470+
```cjs
419471
const {
420472
performance,
421473
PerformanceObserver,
@@ -1256,7 +1308,22 @@ changes:
12561308
`PerformanceObserver` objects provide notifications when new
12571309
`PerformanceEntry` instances have been added to the Performance Timeline.
12581310

1259-
```js
1311+
```mjs
1312+
import { performance, PerformanceObserver } from 'node:perf_hooks';
1313+
1314+
const obs = new PerformanceObserver((list, observer) => {
1315+
console.log(list.getEntries());
1316+
1317+
performance.clearMarks();
1318+
performance.clearMeasures();
1319+
observer.disconnect();
1320+
});
1321+
obs.observe({ entryTypes: ['mark'], buffered: true });
1322+
1323+
performance.mark('test');
1324+
```
1325+
1326+
```cjs
12601327
const {
12611328
performance,
12621329
PerformanceObserver,
@@ -1322,7 +1389,19 @@ Subscribes the {PerformanceObserver} instance to notifications of new
13221389
{PerformanceEntry} instances identified either by `options.entryTypes`
13231390
or `options.type`:
13241391

1325-
```js
1392+
```mjs
1393+
import { performance, PerformanceObserver } from 'node:perf_hooks';
1394+
1395+
const obs = new PerformanceObserver((list, observer) => {
1396+
// Called once asynchronously. `list` contains three items.
1397+
});
1398+
obs.observe({ type: 'mark' });
1399+
1400+
for (let n = 0; n < 3; n++)
1401+
performance.mark(`test${n}`);
1402+
```
1403+
1404+
```cjs
13261405
const {
13271406
performance,
13281407
PerformanceObserver,
@@ -1366,7 +1445,41 @@ added: v8.5.0
13661445
Returns a list of `PerformanceEntry` objects in chronological order
13671446
with respect to `performanceEntry.startTime`.
13681447

1369-
```js
1448+
```mjs
1449+
import { performance, PerformanceObserver } from 'node:perf_hooks';
1450+
1451+
const obs = new PerformanceObserver((perfObserverList, observer) => {
1452+
console.log(perfObserverList.getEntries());
1453+
/**
1454+
* [
1455+
* PerformanceEntry {
1456+
* name: 'test',
1457+
* entryType: 'mark',
1458+
* startTime: 81.465639,
1459+
* duration: 0,
1460+
* detail: null
1461+
* },
1462+
* PerformanceEntry {
1463+
* name: 'meow',
1464+
* entryType: 'mark',
1465+
* startTime: 81.860064,
1466+
* duration: 0,
1467+
* detail: null
1468+
* }
1469+
* ]
1470+
*/
1471+
1472+
performance.clearMarks();
1473+
performance.clearMeasures();
1474+
observer.disconnect();
1475+
});
1476+
obs.observe({ type: 'mark' });
1477+
1478+
performance.mark('test');
1479+
performance.mark('meow');
1480+
```
1481+
1482+
```cjs
13701483
const {
13711484
performance,
13721485
PerformanceObserver,
@@ -1418,7 +1531,49 @@ with respect to `performanceEntry.startTime` whose `performanceEntry.name` is
14181531
equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to
14191532
`type`.
14201533

1421-
```js
1534+
```mjs
1535+
import { performance, PerformanceObserver } from 'node:perf_hooks';
1536+
1537+
const obs = new PerformanceObserver((perfObserverList, observer) => {
1538+
console.log(perfObserverList.getEntriesByName('meow'));
1539+
/**
1540+
* [
1541+
* PerformanceEntry {
1542+
* name: 'meow',
1543+
* entryType: 'mark',
1544+
* startTime: 98.545991,
1545+
* duration: 0,
1546+
* detail: null
1547+
* }
1548+
* ]
1549+
*/
1550+
console.log(perfObserverList.getEntriesByName('nope')); // []
1551+
1552+
console.log(perfObserverList.getEntriesByName('test', 'mark'));
1553+
/**
1554+
* [
1555+
* PerformanceEntry {
1556+
* name: 'test',
1557+
* entryType: 'mark',
1558+
* startTime: 63.518931,
1559+
* duration: 0,
1560+
* detail: null
1561+
* }
1562+
* ]
1563+
*/
1564+
console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
1565+
1566+
performance.clearMarks();
1567+
performance.clearMeasures();
1568+
observer.disconnect();
1569+
});
1570+
obs.observe({ entryTypes: ['mark', 'measure'] });
1571+
1572+
performance.mark('test');
1573+
performance.mark('meow');
1574+
```
1575+
1576+
```cjs
14221577
const {
14231578
performance,
14241579
PerformanceObserver,
@@ -1476,7 +1631,40 @@ Returns a list of `PerformanceEntry` objects in chronological order
14761631
with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`
14771632
is equal to `type`.
14781633

1479-
```js
1634+
```mjs
1635+
import { performance, PerformanceObserver } from 'node:perf_hooks';
1636+
1637+
const obs = new PerformanceObserver((perfObserverList, observer) => {
1638+
console.log(perfObserverList.getEntriesByType('mark'));
1639+
/**
1640+
* [
1641+
* PerformanceEntry {
1642+
* name: 'test',
1643+
* entryType: 'mark',
1644+
* startTime: 55.897834,
1645+
* duration: 0,
1646+
* detail: null
1647+
* },
1648+
* PerformanceEntry {
1649+
* name: 'meow',
1650+
* entryType: 'mark',
1651+
* startTime: 56.350146,
1652+
* duration: 0,
1653+
* detail: null
1654+
* }
1655+
* ]
1656+
*/
1657+
performance.clearMarks();
1658+
performance.clearMeasures();
1659+
observer.disconnect();
1660+
});
1661+
obs.observe({ type: 'mark' });
1662+
1663+
performance.mark('test');
1664+
performance.mark('meow');
1665+
```
1666+
1667+
```cjs
14801668
const {
14811669
performance,
14821670
PerformanceObserver,
@@ -1554,7 +1742,23 @@ event loop. That is, a delay in the loop will cause a delay in the execution
15541742
of the timer, and those delays are specifically what this API is intended to
15551743
detect.
15561744

1557-
```js
1745+
```mjs
1746+
import { monitorEventLoopDelay } from 'node:perf_hooks';
1747+
1748+
const h = monitorEventLoopDelay({ resolution: 20 });
1749+
h.enable();
1750+
// Do something.
1751+
h.disable();
1752+
console.log(h.min);
1753+
console.log(h.max);
1754+
console.log(h.mean);
1755+
console.log(h.stddev);
1756+
console.log(h.percentiles);
1757+
console.log(h.percentile(50));
1758+
console.log(h.percentile(99));
1759+
```
1760+
1761+
```cjs
15581762
const { monitorEventLoopDelay } = require('node:perf_hooks');
15591763
const h = monitorEventLoopDelay({ resolution: 20 });
15601764
h.enable();
@@ -1822,7 +2026,42 @@ The following example uses the [Async Hooks][] and Performance APIs to measure
18222026
the actual duration of a Timeout operation (including the amount of time it took
18232027
to execute the callback).
18242028

1825-
```js
2029+
```mjs
2030+
import { createHook } from 'node:async_hooks';
2031+
import { performance, PerformanceObserver } from 'node:perf_hooks';
2032+
2033+
const set = new Set();
2034+
const hook = createHook({
2035+
init(id, type) {
2036+
if (type === 'Timeout') {
2037+
performance.mark(`Timeout-${id}-Init`);
2038+
set.add(id);
2039+
}
2040+
},
2041+
destroy(id) {
2042+
if (set.has(id)) {
2043+
set.delete(id);
2044+
performance.mark(`Timeout-${id}-Destroy`);
2045+
performance.measure(`Timeout-${id}`,
2046+
`Timeout-${id}-Init`,
2047+
`Timeout-${id}-Destroy`);
2048+
}
2049+
},
2050+
});
2051+
hook.enable();
2052+
2053+
const obs = new PerformanceObserver((list, observer) => {
2054+
console.log(list.getEntries()[0]);
2055+
performance.clearMarks();
2056+
performance.clearMeasures();
2057+
observer.disconnect();
2058+
});
2059+
obs.observe({ entryTypes: ['measure'], buffered: true });
2060+
2061+
setTimeout(() => {}, 1000);
2062+
```
2063+
2064+
```cjs
18262065
'use strict';
18272066
const async_hooks = require('node:async_hooks');
18282067
const {
@@ -1868,7 +2107,29 @@ dependencies:
18682107

18692108
<!-- eslint-disable no-global-assign -->
18702109

1871-
```js
2110+
```mjs
2111+
import { performance, PerformanceObserver } from 'node:perf_hooks';
2112+
2113+
// Activate the observer
2114+
const obs = new PerformanceObserver((list) => {
2115+
const entries = list.getEntries();
2116+
entries.forEach((entry) => {
2117+
console.log(`import('${entry[0]}')`, entry.duration);
2118+
});
2119+
performance.clearMarks();
2120+
performance.clearMeasures();
2121+
obs.disconnect();
2122+
});
2123+
obs.observe({ entryTypes: ['function'], buffered: true });
2124+
2125+
const timedImport = performance.timerify(async (module) => {
2126+
return await import(module);
2127+
});
2128+
2129+
await timedImport('some-module');
2130+
```
2131+
2132+
```cjs
18722133
'use strict';
18732134
const {
18742135
performance,
@@ -1904,7 +2165,28 @@ it means the time interval between starting the request and receiving the
19042165
response, and for HTTP request, it means the time interval between receiving
19052166
the request and sending the response:
19062167

1907-
```js
2168+
```mjs
2169+
import { PerformanceObserver } from 'node:perf_hooks';
2170+
import { createServer, get } from 'node:http';
2171+
2172+
const obs = new PerformanceObserver((items) => {
2173+
items.getEntries().forEach((item) => {
2174+
console.log(item);
2175+
});
2176+
});
2177+
2178+
obs.observe({ entryTypes: ['http'] });
2179+
2180+
const PORT = 8080;
2181+
2182+
createServer((req, res) => {
2183+
res.end('ok');
2184+
}).listen(PORT, () => {
2185+
get(`http://127.0.0.1:${PORT}`);
2186+
});
2187+
```
2188+
2189+
```cjs
19082190
'use strict';
19092191
const { PerformanceObserver } = require('node:perf_hooks');
19102192
const http = require('node:http');
@@ -1928,7 +2210,25 @@ http.createServer((req, res) => {
19282210

19292211
### Measuring how long the `net.connect` (only for TCP) takes when the connection is successful
19302212

1931-
```js
2213+
```mjs
2214+
import { PerformanceObserver } from 'node:perf_hooks';
2215+
import { connect, createServer } from 'node:net';
2216+
2217+
const obs = new PerformanceObserver((items) => {
2218+
items.getEntries().forEach((item) => {
2219+
console.log(item);
2220+
});
2221+
});
2222+
obs.observe({ entryTypes: ['net'] });
2223+
const PORT = 8080;
2224+
createServer((socket) => {
2225+
socket.destroy();
2226+
}).listen(PORT, () => {
2227+
connect(PORT);
2228+
});
2229+
```
2230+
2231+
```cjs
19322232
'use strict';
19332233
const { PerformanceObserver } = require('node:perf_hooks');
19342234
const net = require('node:net');
@@ -1948,7 +2248,21 @@ net.createServer((socket) => {
19482248

19492249
### Measuring how long the DNS takes when the request is successful
19502250

1951-
```js
2251+
```mjs
2252+
import { PerformanceObserver } from 'node:perf_hooks';
2253+
import { lookup, promises } from 'node:dns';
2254+
2255+
const obs = new PerformanceObserver((items) => {
2256+
items.getEntries().forEach((item) => {
2257+
console.log(item);
2258+
});
2259+
});
2260+
obs.observe({ entryTypes: ['dns'] });
2261+
lookup('localhost', () => {});
2262+
promises.resolve('localhost');
2263+
```
2264+
2265+
```cjs
19522266
'use strict';
19532267
const { PerformanceObserver } = require('node:perf_hooks');
19542268
const dns = require('node:dns');

0 commit comments

Comments
 (0)
Please sign in to comment.