GeezerVison is showing github.com — perf_hooks: add histogram.snapshot() · nodejs/node@f1732d2
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboard +24Lines changed: 24 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +const assert = require('assert'); | | 4 | +const common = require('../common.js'); | | 5 | +const { createHistogram } = require('perf_hooks'); | | 6 | + | | 7 | +const bench = common.createBenchmark(main, { | | 8 | + n: [1e3], | | 9 | + highest: [1e6, Number.MAX_SAFE_INTEGER], | | 10 | + figures: [2, 3], | | 11 | +}); | | 12 | + | | 13 | +let snapshot; | | 14 | + | | 15 | +function main({ n, highest, figures }) { | | 16 | + const histogram = createHistogram({ highest, figures }); | | 17 | + for (let i = 1; i <= 1e4; i++) histogram.record(i); | | 18 | + | | 19 | + bench.start(); | | 20 | + for (let i = 0; i < n; i++) snapshot = histogram.snapshot(); | | 21 | + bench.end(n); | | 22 | + | | 23 | + assert.strictEqual(snapshot.count, 1e4); | | 24 | +} |
Collapse file Copy file name to clipboardExpand all lines: doc/api/perf_hooks.md +32Lines changed: 32 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -2618,6 +2618,38 @@ distribution. A positive value indicates a right-skewed distribution | 2618 | 2618 | (longer right tail, common for latency data); a negative value | 2619 | 2619 | indicates a left-skewed distribution. | 2620 | 2620 |
| | 2621 | +### `histogram.snapshot()` | | 2622 | + | | 2623 | +<!-- YAML | | 2624 | +added: REPLACEME | | 2625 | +--> | | 2626 | + | | 2627 | +* Returns: {Histogram} | | 2628 | + | | 2629 | +Returns a new, independent {Histogram} containing a copy of this histogram's | | 2630 | +current state: its configuration, recorded values, `exceeds` count, and EWMA | | 2631 | +state. Values recorded into this histogram after this method returns, and later | | 2632 | +calls to `reset()`, do not change the returned histogram. This provides a stable | | 2633 | +view of a histogram that is still recording, such as an enabled {ELDHistogram}. | | 2634 | + | | 2635 | +Values cannot be recorded into the returned histogram. Taking a snapshot copies | | 2636 | +every bucket, so both its time and memory cost depend on the histogram's | | 2637 | +`lowest`, `highest`, and `figures` configuration rather than on the number of | | 2638 | +recorded values. | | 2639 | + | | 2640 | +```js | | 2641 | +const { monitorEventLoopDelay } = require('node:perf_hooks'); | | 2642 | + | | 2643 | +const histogram = monitorEventLoopDelay(); | | 2644 | +histogram.enable(); | | 2645 | + | | 2646 | +setTimeout(() => { | | 2647 | + const snapshot = histogram.snapshot(); | | 2648 | + console.log(snapshot.percentile(99)); | | 2649 | + histogram.disable(); | | 2650 | +}, 1000); | | 2651 | +``` | | 2652 | + | 2621 | 2653 | ### `histogram.stddev` | 2622 | 2654 |
| 2623 | 2655 | <!-- YAML | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/histogram.js +12Lines changed: 12 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -679,6 +679,18 @@ class Histogram { | 679 | 679 | this[kHandle]?.reset(); | 680 | 680 | } | 681 | 681 |
| | 682 | + /** | | 683 | + * Returns a new, independent histogram containing a copy of this | | 684 | + * histogram's current state. Values cannot be recorded into the returned | | 685 | + * histogram. | | 686 | + * @returns {Histogram} | | 687 | + */ | | 688 | + snapshot() { | | 689 | + if (!isHistogram(this)) | | 690 | + throw new ERR_INVALID_THIS('Histogram'); | | 691 | + return new ClonedHistogram(this[kHandle].snapshot()); | | 692 | + } | | 693 | + | 682 | 694 | [kClone]() { | 683 | 695 | const handle = this[kHandle]; | 684 | 696 | return { | |
Collapse file Copy file name to clipboardExpand all lines: src/histogram.cc +59-10Lines changed: 59 additions & 10 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -76,6 +76,51 @@ std::shared_ptr<Histogram> Histogram::Create(const Options& options) { | 76 | 76 | return std::make_shared<Histogram>(HistogramPointer(histogram), options); | 77 | 77 | } | 78 | 78 |
| | 79 | +namespace { | | 80 | +// Copies the recorded data of `source` into `target`, which must have been | | 81 | +// initialized with the same layout. The caller must hold a lock that prevents | | 82 | +// `source` from being modified during the copy. | | 83 | +void CopyRecordedData(hdr_histogram* target, const hdr_histogram* source) { | | 84 | + CHECK_EQ(target->counts_len, source->counts_len); | | 85 | + target->min_value = source->min_value; | | 86 | + target->max_value = source->max_value; | | 87 | + target->normalizing_index_offset = source->normalizing_index_offset; | | 88 | + target->conversion_ratio = source->conversion_ratio; | | 89 | + target->total_count = source->total_count; | | 90 | + std::memcpy(target->counts, | | 91 | + source->counts, | | 92 | + source->counts_len * sizeof(*source->counts)); | | 93 | +} | | 94 | +} // namespace | | 95 | + | | 96 | +std::shared_ptr<Histogram> Histogram::Clone() const { | | 97 | + // The layout is fixed when the histogram is created, so the copy can be | | 98 | + // allocated without holding the lock. | | 99 | + hdr_histogram* copy; | | 100 | + if (hdr_init(histogram_->lowest_discernible_value, | | 101 | + histogram_->highest_trackable_value, | | 102 | + histogram_->significant_figures, | | 103 | + ©) != 0) { | | 104 | + return {}; | | 105 | + } | | 106 | + auto clone = std::make_shared<Histogram>(HistogramPointer(copy), Options{}); | | 107 | + | | 108 | + // Every member that holds recorded or statistical state must be copied | | 109 | + // here. The recorded snapshot cache is not copied; the clone builds its own | | 110 | + // on demand. | | 111 | + RwLock::ScopedReadLock lock(mutex_); | | 112 | + CopyRecordedData(clone->histogram_.get(), histogram_.get()); | | 113 | + clone->prev_ = prev_; | | 114 | + clone->exceeds_ = exceeds_; | | 115 | + clone->ewma_alpha_ = ewma_alpha_; | | 116 | + clone->ewma_mean_ = ewma_mean_; | | 117 | + clone->ewma_variance_ = ewma_variance_; | | 118 | + clone->ewma_initialized_ = ewma_initialized_; | | 119 | + clone->threshold_ = threshold_; | | 120 | + clone->ewma_error_rate_ = ewma_error_rate_; | | 121 | + return clone; | | 122 | +} | | 123 | + | 79 | 124 | void Histogram::MemoryInfo(MemoryTracker* tracker) const { | 80 | 125 | tracker->TrackFieldWithSize("histogram", GetMemorySize()); | 81 | 126 | tracker->TrackFieldWithSize("qrde_snapshot", | @@ -158,16 +203,7 @@ Histogram::RecordedSnapshotSource Histogram::GetRecordedSnapshotSource( | 158 | 203 | return source; | 159 | 204 | } | 160 | 205 |
| 161 | | - CHECK_EQ(source.histogram->counts_len, histogram_->counts_len); | 162 | | - source.histogram->min_value = histogram_->min_value; | 163 | | - source.histogram->max_value = histogram_->max_value; | 164 | | - source.histogram->normalizing_index_offset = | 165 | | - histogram_->normalizing_index_offset; | 166 | | - source.histogram->conversion_ratio = histogram_->conversion_ratio; | 167 | | - source.histogram->total_count = histogram_->total_count; | 168 | | - std::memcpy(source.histogram->counts, | 169 | | - histogram_->counts, | 170 | | - histogram_->counts_len * sizeof(*histogram_->counts)); | | 206 | + CopyRecordedData(source.histogram.get(), histogram_.get()); | 171 | 207 | return source; | 172 | 208 | } | 173 | 209 |
| @@ -1842,6 +1878,7 @@ void HistogramImpl::AddMethods(Isolate* isolate, Local<FunctionTemplate> tmpl) { | 1842 | 1878 | GetEwmaErrorRate, | 1843 | 1879 | &fast_get_ewma_error_rate_); | 1844 | 1880 | SetProtoMethodNoSideEffect(isolate, tmpl, "export", DoExport); | | 1881 | + SetProtoMethodNoSideEffect(isolate, tmpl, "snapshot", DoSnapshot); | 1845 | 1882 | SetFastMethod(isolate, instance, "reset", DoReset, &fast_reset_); | 1846 | 1883 | } | 1847 | 1884 |
| @@ -1891,6 +1928,7 @@ void HistogramImpl::RegisterExternalReferences( | 1891 | 1928 | registry->Register(GetEwmaStddev); | 1892 | 1929 | registry->Register(GetEwmaErrorRate); | 1893 | 1930 | registry->Register(DoExport); | | 1931 | + registry->Register(DoSnapshot); | 1894 | 1932 | registry->Register(fast_get_ewma_mean_); | 1895 | 1933 | registry->Register(fast_get_ewma_stddev_); | 1896 | 1934 | registry->Register(fast_get_ewma_error_rate_); | @@ -3020,6 +3058,17 @@ void HistogramImpl::DoImport(const FunctionCallbackInfo<Value>& args) { | 3020 | 3058 | args.GetReturnValue().Set(obj); | 3021 | 3059 | } | 3022 | 3060 |
| | 3061 | +void HistogramImpl::DoSnapshot(const FunctionCallbackInfo<Value>& args) { | | 3062 | + Environment* env = Environment::GetCurrent(args); | | 3063 | + HistogramImpl* histogram = HistogramImpl::FromJSObject(args.This()); | | 3064 | + std::shared_ptr<Histogram> snapshot = (*histogram)->Clone(); | | 3065 | + if (!snapshot) return THROW_ERR_MEMORY_ALLOCATION_FAILED(env); | | 3066 | + | | 3067 | + BaseObjectPtr<HistogramBase> result = | | 3068 | + HistogramBase::Create(env, std::move(snapshot)); | | 3069 | + if (result) args.GetReturnValue().Set(result->object()); | | 3070 | +} | | 3071 | + | 3023 | 3072 | void HistogramImpl::GetPercentilesAt(const FunctionCallbackInfo<Value>& args) { | 3024 | 3073 | Environment* env = Environment::GetCurrent(args); | 3025 | 3074 | HistogramImpl* histogram = HistogramImpl::FromJSObject(args.This()); | |
Collapse file Copy file name to clipboardExpand all lines: src/histogram.h +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -61,6 +61,10 @@ class Histogram : public MemoryRetainer { | 61 | 61 | // Factory method that returns nullptr on hdr_init failure. | 62 | 62 | static std::shared_ptr<Histogram> Create(const Options& options); | 63 | 63 |
| | 64 | + // Returns an independent copy of this histogram's current state, or nullptr | | 65 | + // if the copy cannot be allocated. | | 66 | + std::shared_ptr<Histogram> Clone() const; | | 67 | + | 64 | 68 | Histogram(HistogramPointer histogram, const Options& options); | 65 | 69 | virtual ~Histogram() = default; | 66 | 70 |
| @@ -237,6 +241,7 @@ class HistogramImpl { | 237 | 241 | static void GetEwmaErrorRate(const v8::FunctionCallbackInfo<v8::Value>& args); | 238 | 242 | static void DoExport(const v8::FunctionCallbackInfo<v8::Value>& args); | 239 | 243 | static void DoImport(const v8::FunctionCallbackInfo<v8::Value>& args); | | 244 | + static void DoSnapshot(const v8::FunctionCallbackInfo<v8::Value>& args); | 240 | 245 |
| 241 | 246 | static void FastReset(v8::Local<v8::Value> receiver); | 242 | 247 | static double FastGetCount(v8::Local<v8::Value> receiver); | |
Collapse file Copy file name to clipboard +138Lines changed: 138 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +const common = require('../common'); | | 4 | +const assert = require('assert'); | | 5 | +const { setTimeout: delay } = require('timers/promises'); | | 6 | +const { inspect } = require('util'); | | 7 | +const { | | 8 | + createHistogram, | | 9 | + monitorEventLoopDelay, | | 10 | +} = require('perf_hooks'); | | 11 | + | | 12 | +function assertSameState(actual, expected) { | | 13 | + assert.strictEqual(actual.countBigInt, expected.countBigInt); | | 14 | + assert.strictEqual(actual.minBigInt, expected.minBigInt); | | 15 | + assert.strictEqual(actual.maxBigInt, expected.maxBigInt); | | 16 | + assert.strictEqual(actual.exceedsBigInt, expected.exceedsBigInt); | | 17 | + assert.strictEqual(actual.mean, expected.mean); | | 18 | + assert.strictEqual(actual.stddev, expected.stddev); | | 19 | + assert.strictEqual(actual.ewmaMean, expected.ewmaMean); | | 20 | + assert.strictEqual(actual.ewmaStddev, expected.ewmaStddev); | | 21 | + assert.strictEqual(actual.ewmaErrorRate, expected.ewmaErrorRate); | | 22 | + assert.deepStrictEqual(actual.percentilesBigInt, expected.percentilesBigInt); | | 23 | + // The export format also covers the layout, the raw min and max values, | | 24 | + // every bucket count, and the EWMA configuration. | | 25 | + assert.deepStrictEqual(actual.export(), expected.export()); | | 26 | +} | | 27 | + | | 28 | +function assertReadOnly(snapshot) { | | 29 | + assert.strictEqual(snapshot.constructor.name, 'Histogram'); | | 30 | + assert.strictEqual(inspect(snapshot, { depth: -1 }), '[Histogram]'); | | 31 | + for (const name of [ | | 32 | + 'record', | | 33 | + 'recordDelta', | | 34 | + 'recordCorrected', | | 35 | + 'add', | | 36 | + 'subtract', | | 37 | + 'enable', | | 38 | + 'disable', | | 39 | + ]) { | | 40 | + assert.strictEqual(snapshot[name], undefined); | | 41 | + } | | 42 | +} | | 43 | + | | 44 | +{ | | 45 | + const histogram = createHistogram({ | | 46 | + lowest: 1, | | 47 | + highest: 1000, | | 48 | + figures: 2, | | 49 | + halfLife: 8, | | 50 | + threshold: 50, | | 51 | + }); | | 52 | + for (let i = 1; i <= 100; i++) histogram.record(i * 7); | | 53 | + histogram.record(1e6); | | 54 | + assert.strictEqual(histogram.exceeds, 1); | | 55 | + assert.ok(histogram.ewmaErrorRate > 0); | | 56 | + | | 57 | + const snapshot = histogram.snapshot(); | | 58 | + assert.notStrictEqual(snapshot, histogram); | | 59 | + assertReadOnly(snapshot); | | 60 | + assertSameState(snapshot, histogram); | | 61 | + assert.strictEqual(histogram.ksTest(snapshot), 0); | | 62 | + | | 63 | + // A snapshot can be snapshotted and cloned. | | 64 | + const nested = snapshot.snapshot(); | | 65 | + assertReadOnly(nested); | | 66 | + assertSameState(nested, snapshot); | | 67 | + assertSameState(structuredClone(snapshot), snapshot); | | 68 | + | | 69 | + // Changes to the source histogram do not change the snapshot. | | 70 | + const exported = snapshot.export(); | | 71 | + histogram.record(3); | | 72 | + histogram.recordCorrected(900, 100); | | 73 | + histogram.record(1e6); | | 74 | + assert.deepStrictEqual(snapshot.export(), exported); | | 75 | + assert.strictEqual(snapshot.count, 100); | | 76 | + assert.strictEqual(snapshot.exceeds, 1); | | 77 | + | | 78 | + histogram.reset(); | | 79 | + assert.strictEqual(histogram.count, 0); | | 80 | + assert.deepStrictEqual(snapshot.export(), exported); | | 81 | + | | 82 | + // Resetting a snapshot does not change the source histogram or other | | 83 | + // snapshots. | | 84 | + histogram.record(5); | | 85 | + const current = histogram.snapshot(); | | 86 | + snapshot.reset(); | | 87 | + assert.strictEqual(snapshot.count, 0); | | 88 | + assert.strictEqual(histogram.count, 1); | | 89 | + assert.strictEqual(current.count, 1); | | 90 | + assert.deepStrictEqual(nested.export(), exported); | | 91 | +} | | 92 | + | | 93 | +{ | | 94 | + // Empty histograms, with and without EWMA state. | | 95 | + for (const options of [undefined, { halfLife: 10, threshold: 1 }]) { | | 96 | + const histogram = createHistogram(options); | | 97 | + const snapshot = histogram.snapshot(); | | 98 | + assertReadOnly(snapshot); | | 99 | + assert.strictEqual(snapshot.count, 0); | | 100 | + assert.strictEqual(snapshot.minBigInt, 9223372036854775807n); | | 101 | + assert.strictEqual(snapshot.maxBigInt, 0n); | | 102 | + assertSameState(snapshot, histogram); | | 103 | + } | | 104 | +} | | 105 | + | | 106 | +{ | | 107 | + const histogram = createHistogram(); | | 108 | + assert.throws(() => histogram.snapshot.call({}), { | | 109 | + code: 'ERR_INVALID_THIS', | | 110 | + }); | | 111 | +} | | 112 | + | | 113 | +async function testEventLoopDelay(options) { | | 114 | + const histogram = monitorEventLoopDelay(options); | | 115 | + histogram.enable(); | | 116 | + while (histogram.count < 3) await delay(1); | | 117 | + | | 118 | + // Samples are only recorded while the event loop is running, so none can | | 119 | + // be added while this code runs synchronously. | | 120 | + const snapshot = histogram.snapshot(); | | 121 | + assertReadOnly(snapshot); | | 122 | + assertSameState(snapshot, histogram); | | 123 | + | | 124 | + const exported = snapshot.export(); | | 125 | + const count = histogram.count; | | 126 | + while (histogram.count === count) await delay(1); | | 127 | + assert.deepStrictEqual(snapshot.export(), exported); | | 128 | + | | 129 | + histogram.disable(); | | 130 | + histogram.reset(); | | 131 | + assert.strictEqual(histogram.count, 0); | | 132 | + assert.deepStrictEqual(snapshot.export(), exported); | | 133 | +} | | 134 | + | | 135 | +(async () => { | | 136 | + await testEventLoopDelay({ resolution: 1 }); | | 137 | + await testEventLoopDelay({ samplePerIteration: true }); | | 138 | +})().then(common.mustCall()); |
Collapse file Copy file name to clipboardExpand all lines: typings/internalBinding/performance.d.ts +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -41,6 +41,7 @@ declare namespace InternalPerformanceBinding { | 41 | 41 | ewmaMean(): number; | 42 | 42 | ewmaStddev(): number; | 43 | 43 | ewmaErrorRate(): number; | | 44 | + snapshot(): Histogram; | 44 | 45 | } | 45 | 46 |
| 46 | 47 | interface ELDHistogram extends HistogramBase { | |
|