diff --git a/benchmark/perf_hooks/histogram-snapshot.js b/benchmark/perf_hooks/histogram-snapshot.js new file mode 100644 index 00000000000..79b13fecb0f --- /dev/null +++ b/benchmark/perf_hooks/histogram-snapshot.js @@ -0,0 +1,24 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common.js'); +const { createHistogram } = require('perf_hooks'); + +const bench = common.createBenchmark(main, { + n: [1e3], + highest: [1e6, Number.MAX_SAFE_INTEGER], + figures: [2, 3], +}); + +let snapshot; + +function main({ n, highest, figures }) { + const histogram = createHistogram({ highest, figures }); + for (let i = 1; i <= 1e4; i++) histogram.record(i); + + bench.start(); + for (let i = 0; i < n; i++) snapshot = histogram.snapshot(); + bench.end(n); + + assert.strictEqual(snapshot.count, 1e4); +} diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index ca25c38ffdf..028d6e0832a 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -2618,6 +2618,38 @@ distribution. A positive value indicates a right-skewed distribution (longer right tail, common for latency data); a negative value indicates a left-skewed distribution. +### `histogram.snapshot()` + + + +* Returns: {Histogram} + +Returns a new, independent {Histogram} containing a copy of this histogram's +current state: its configuration, recorded values, `exceeds` count, and EWMA +state. Values recorded into this histogram after this method returns, and later +calls to `reset()`, do not change the returned histogram. This provides a stable +view of a histogram that is still recording, such as an enabled {ELDHistogram}. + +Values cannot be recorded into the returned histogram. Taking a snapshot copies +every bucket, so both its time and memory cost depend on the histogram's +`lowest`, `highest`, and `figures` configuration rather than on the number of +recorded values. + +```js +const { monitorEventLoopDelay } = require('node:perf_hooks'); + +const histogram = monitorEventLoopDelay(); +histogram.enable(); + +setTimeout(() => { + const snapshot = histogram.snapshot(); + console.log(snapshot.percentile(99)); + histogram.disable(); +}, 1000); +``` + ### `histogram.stddev`