diff --git a/src/AutoCountsHistogram.fc.spec.ts b/src/AutoCountsHistogram.fc.spec.ts new file mode 100644 index 0000000..b41e597 --- /dev/null +++ b/src/AutoCountsHistogram.fc.spec.ts @@ -0,0 +1,94 @@ +import * as fc from "fast-check"; +import AutoCountsHistogram from "./AutoCountsHistogram"; +import Float64Histogram from "./Float64Histogram"; + +const runFromStryker = __dirname.includes("stryker"); + +const runnerOptions = { + numRuns: runFromStryker ? 10 : 300, + verbose: true, +}; + +const HIGHEST = 1000000; + +// Counts around each width boundary, plus small and mid-sized ones, so random +// sequences cross 2^8, 2^16 and 2^32 often. +const countArb = fc.oneof( + fc.integer({ min: 1, max: 300 }), + fc.constantFrom(255, 256, 257, 65535, 65536, 65537, 2 ** 32 - 1, 2 ** 32), + fc.integer({ min: 1, max: 2 ** 33 }) +); + +const valueArb = fc.integer({ min: 1, max: HIGHEST }); + +type Op = + | { kind: "record"; value: number; count: number } + | { kind: "subtract"; value: number; count: number } + | { kind: "add"; entries: Array<[number, number]> }; + +const opArb: fc.Arbitrary = fc.oneof( + fc + .record({ value: valueArb, count: countArb }) + .map(({ value, count }) => ({ kind: "record", value, count }) as Op), + fc + .record({ value: valueArb, count: fc.integer({ min: 1, max: 1000 }) }) + .map(({ value, count }) => ({ kind: "subtract", value, count }) as Op), + fc + .array(fc.tuple(valueArb, countArb), { minLength: 1, maxLength: 5 }) + .map((entries) => ({ kind: "add", entries }) as Op) +); + +describe("AutoCountsHistogram property: matches a Float64 twin", () => { + it("keeps every count, total, extremes and percentiles equal under random operations", () => { + fc.assert( + fc.property(fc.array(opArb, { minLength: 1, maxLength: 40 }), (ops) => { + const auto = new AutoCountsHistogram(1, HIGHEST, 3); + const twin = new Float64Histogram(1, HIGHEST, 3); + let previousWidth = auto.currentBitBucketSize; + + for (const op of ops) { + if (op.kind === "record") { + auto.recordValueWithCount(op.value, op.count); + twin.recordValueWithCount(op.value, op.count); + } else if (op.kind === "subtract") { + // Only subtract what the twin holds, so no count goes negative. + const index = twin.countsArrayIndex(op.value); + if (twin.getCountAtIndex(index) < op.count) continue; + auto.recordValueWithCount(op.value, -op.count); + twin.recordValueWithCount(op.value, -op.count); + } else { + const other = new Float64Histogram(1, HIGHEST, 3); + for (const [value, count] of op.entries) { + other.recordValueWithCount(value, count); + } + const otherAuto = new AutoCountsHistogram(1, HIGHEST, 3); + for (const [value, count] of op.entries) { + otherAuto.recordValueWithCount(value, count); + } + auto.add(otherAuto); + twin.add(other); + } + + // Width only ever grows, and always holds the largest count. + expect(auto.currentBitBucketSize).toBeGreaterThanOrEqual( + previousWidth + ); + previousWidth = auto.currentBitBucketSize; + } + + expect(auto.totalCount).toBe(twin.totalCount); + expect(auto.maxValue).toBe(twin.maxValue); + expect(auto.minNonZeroValue).toBe(twin.minNonZeroValue); + for (let i = 0; i < twin.countsArrayLength; i++) { + expect(auto.getCountAtIndex(i)).toBe(twin.getCountAtIndex(i)); + } + for (const p of [0, 50, 90, 99, 99.9, 100]) { + expect(auto.getValueAtPercentile(p)).toBe( + twin.getValueAtPercentile(p) + ); + } + }), + runnerOptions + ); + }); +}); diff --git a/src/AutoCountsHistogram.spec.ts b/src/AutoCountsHistogram.spec.ts new file mode 100644 index 0000000..17373b0 --- /dev/null +++ b/src/AutoCountsHistogram.spec.ts @@ -0,0 +1,270 @@ +import AutoCountsHistogram from "./AutoCountsHistogram"; +import Float64Histogram from "./Float64Histogram"; +import Int32Histogram from "./Int32Histogram"; +import { build } from "./index"; +import JsHistogram from "./JsHistogram"; +import type { BitBucketSize } from "./Histogram"; +import { + encodeIntoCompressedBase64, + decodeFromCompressedBase64, +} from "./encoding"; + +const newAuto = () => new AutoCountsHistogram(1, 1000000, 3); +const newTwin = () => new Float64Histogram(1, 1000000, 3); + +describe("AutoCountsHistogram", () => { + it("starts with 8-bit counts", () => { + expect(newAuto().currentBitBucketSize).toBe(8); + }); + + it("is selected by build({ bitBucketSize: 'auto' })", () => { + const histogram = build({ bitBucketSize: "auto" }) as JsHistogram; + expect(histogram).toBeInstanceOf(AutoCountsHistogram); + expect((histogram as AutoCountsHistogram).currentBitBucketSize).toBe(8); + }); + + it("stays at 8 bits while every count is at most 255", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(3, 255); + histogram.addToCountAtIndex(4, 200); + expect(histogram.currentBitBucketSize).toBe(8); + expect(histogram.getCountAtIndex(3)).toBe(255); + expect(histogram.getCountAtIndex(4)).toBe(200); + }); + + it("promotes 8 -> 16 bits at 256 without wrapping", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(3, 255); + histogram.incrementCountAtIndex(3); + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.getCountAtIndex(3)).toBe(256); + }); + + it("promotes 16 -> 32 bits at 65536 without wrapping", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(3, 65535); + expect(histogram.currentBitBucketSize).toBe(16); + histogram.addToCountAtIndex(3, 1); + expect(histogram.currentBitBucketSize).toBe(32); + expect(histogram.getCountAtIndex(3)).toBe(65536); + }); + + it("promotes 32 -> 64 bits at 2^32 without wrapping", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(3, 2 ** 32 - 1); + expect(histogram.currentBitBucketSize).toBe(32); + histogram.incrementCountAtIndex(3); + expect(histogram.currentBitBucketSize).toBe(64); + expect(histogram.getCountAtIndex(3)).toBe(2 ** 32); + }); + + it("jumps straight to the needed width for a large count", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(0, 2 ** 40); + expect(histogram.currentBitBucketSize).toBe(64); + expect(histogram.getCountAtIndex(0)).toBe(2 ** 40); + }); + + it("preserves every count across promotions", () => { + const histogram = newAuto(); + const twin = newTwin(); + const counts: Array<[number, number]> = [ + [1, 7], + [2, 255], + [5, 300], + [9, 70000], + [10, 5_000_000_000], + ]; + for (const [index, count] of counts) { + histogram.setCountAtIndex(index, count); + twin.setCountAtIndex(index, count); + } + expect(histogram.currentBitBucketSize).toBe(64); + for (let i = 0; i < histogram.countsArrayLength; i++) { + expect(histogram.getCountAtIndex(i)).toBe(twin.getCountAtIndex(i)); + } + }); + + it("refuses counts above MAX_SAFE_INTEGER instead of storing them", () => { + const histogram = newAuto(); + expect(() => + histogram.setCountAtIndex(0, Number.MAX_SAFE_INTEGER + 2) + ).toThrow(); + }); + + it("refuses negative counts in every width", () => { + const histogram = newAuto(); + histogram.setCountAtIndex(0, 1); + expect(() => histogram.addToCountAtIndex(0, -2)).toThrow(); + histogram.setCountAtIndex(1, 1000); + expect(histogram.currentBitBucketSize).toBe(16); + expect(() => histogram.setCountAtIndex(1, -1)).toThrow(); + expect(histogram.getCountAtIndex(1)).toBe(1000); + }); + + it("keeps totalCount, maxValue and minNonZeroValue exact across promotion", () => { + const histogram = newAuto(); + const twin = newTwin(); + for (const h of [histogram, twin]) { + h.recordValueWithCount(17, 100000); + h.recordValueWithCount(999999, 3); + h.recordValue(4); + } + expect(histogram.currentBitBucketSize).toBe(32); + expect(histogram.totalCount).toBe(twin.totalCount); + expect(histogram.maxValue).toBe(twin.maxValue); + expect(histogram.minNonZeroValue).toBe(twin.minNonZeroValue); + expect(histogram.toJSON()).toStrictEqual(twin.toJSON()); + }); + + it("gives the same percentiles as a Float64 histogram", () => { + const histogram = newAuto(); + const twin = newTwin(); + for (let v = 1; v <= 5000; v++) { + const count = v % 97 === 0 ? 70000 : (v % 13) + 1; + histogram.recordValueWithCount(v, count); + twin.recordValueWithCount(v, count); + } + expect(histogram.currentBitBucketSize).toBe(32); + for (const p of [0, 50, 90, 99, 99.9, 99.99, 100]) { + expect(histogram.getValueAtPercentile(p)).toBe( + twin.getValueAtPercentile(p) + ); + } + expect(histogram.summary).toStrictEqual(twin.summary); + }); + + it("promotes when adding a histogram with larger counts", () => { + const histogram = newAuto(); + histogram.recordValueWithCount(42, 10); + const other = new Int32Histogram(1, 1000000, 3); + other.recordValueWithCount(42, 300); + expect(histogram.currentBitBucketSize).toBe(8); + histogram.add(other); + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe(310); + expect(histogram.totalCount).toBe(310); + }); + + it("keeps the promoted width after subtracting back below 256", () => { + const histogram = newAuto(); + histogram.recordValueWithCount(42, 300); + const other = newAuto(); + other.recordValueWithCount(42, 299); + histogram.subtract(other); + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe(1); + expect(histogram.totalCount).toBe(1); + expect(histogram.getValueAtPercentile(100)).toBe(42); + }); + + it("keeps the width on clearCounts", () => { + const histogram = newAuto(); + histogram.recordValueWithCount(1, 1000); + histogram.clearCounts(); + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(0); + }); + + it("keeps counts when autoResize widens the range after a promotion", () => { + const histogram = new AutoCountsHistogram(1, 2, 3); + histogram.autoResize = true; + histogram.recordValueWithCount(1, 300); + histogram.recordValue(123456); + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.totalCount).toBe(301); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(300); + expect(histogram.getValueAtPercentile(99)).toBeLessThan(1000 + 123456); + }); + + it("promotes when a large count resizes an auto-resizing histogram", () => { + // given + const histogram = new AutoCountsHistogram(1, 2, 3); + histogram.autoResize = true; + // when + histogram.recordValueWithCount(123456, 300); + // then + expect(histogram.currentBitBucketSize).toBe(16); + expect(histogram.totalCount).toBe(300); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(123456))).toBe( + 300 + ); + }); + + it("refuses a negative count before resizing", () => { + // given + const histogram = new AutoCountsHistogram(1, 2, 3); + histogram.autoResize = true; + const highestTrackableValue = histogram.highestTrackableValue; + // when + const recording = () => histogram.recordValueWithCount(123456, -1); + // then + expect(recording).toThrow("negative count"); + expect(histogram.highestTrackableValue).toBe(highestTrackableValue); + }); + + it("copies with coordinated omission correction into an auto histogram", () => { + const histogram = newAuto(); + const twin = newTwin(); + histogram.recordValueWithCount(1000, 300); + twin.recordValueWithCount(1000, 300); + const copy = histogram.copyCorrectedForCoordinatedOmission(100); + expect(copy).toBeInstanceOf(AutoCountsHistogram); + expect(copy.toJSON()).toStrictEqual( + twin.copyCorrectedForCoordinatedOmission(100).toJSON() + ); + }); + + describe("encoding round-trip", () => { + // Largest count that fits each width, so fixed-width decoders do not wrap. + const fixtures: Array<[number, number]> = [ + [8, 255], + [16, 65535], + [32, 2 ** 32 - 1], + [64, 5_000_000_000], + ]; + fixtures.forEach(([width, maxCount]) => { + const targets: BitBucketSize[] = [ + width as BitBucketSize, + 64, + "packed", + "auto", + ]; + targets.forEach((bitBucketSize) => { + it(`encodes a ${width}-bit-wide auto histogram and decodes it into ${bitBucketSize} buckets`, async () => { + const histogram = newAuto(); + histogram.recordValue(5); + histogram.recordValueWithCount(999, maxCount); + expect(histogram.currentBitBucketSize).toBe(width); + const b64 = await encodeIntoCompressedBase64(histogram); + const decoded = await decodeFromCompressedBase64(b64, bitBucketSize); + expect(decoded.toJSON()).toStrictEqual(histogram.toJSON()); + expect(decoded.totalCount).toBe(histogram.totalCount); + expect(decoded.getCountAtIndex(histogram.countsArrayIndex(999))).toBe( + maxCount + ); + }); + }); + }); + + it("decodes into an auto histogram that then promotes", async () => { + const source = new Int32Histogram(1, 1000000, 3); + source.recordValueWithCount(9, 100); + const b64 = await encodeIntoCompressedBase64(source); + const decoded = (await decodeFromCompressedBase64( + b64, + "auto" + )) as AutoCountsHistogram; + expect(decoded.currentBitBucketSize).toBe(8); + decoded.recordValueWithCount(9, 1000); + expect(decoded.currentBitBucketSize).toBe(16); + expect(decoded.totalCount).toBe(1100); + }); + }); + + it("refuses WebAssembly for the auto mode", () => { + expect(() => + build({ bitBucketSize: "auto", useWebAssembly: true }) + ).toThrow("not supported with WebAssembly"); + }); +}); diff --git a/src/AutoCountsHistogram.ts b/src/AutoCountsHistogram.ts new file mode 100644 index 0000000..13d8284 --- /dev/null +++ b/src/AutoCountsHistogram.ts @@ -0,0 +1,156 @@ +/* + * This is a TypeScript port of the original Java version, which was written by + * Gil Tene as described in + * https://github.com/HdrHistogram/HdrHistogram + * and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +import TypedArrayHistogram from "./TypedArrayHistogram"; + +type CountsArrayCtr = ConstructorParameters[0]; + +/** + * Counts widths from narrowest to widest. A histogram starts at the first one + * and moves to the next one the first time a count does not fit in it. + */ +const TIERS: ReadonlyArray<{ + ctr: CountsArrayCtr; + bits: number; + maxCount: number; +}> = [ + { ctr: Uint8Array, bits: 8, maxCount: 0xff }, + { ctr: Uint16Array, bits: 16, maxCount: 0xffff }, + { ctr: Uint32Array, bits: 32, maxCount: 0xffffffff }, + { ctr: Float64Array, bits: 64, maxCount: Number.MAX_SAFE_INTEGER }, +]; + +/** + * Histogram whose counts start at 8 bits per bucket and are widened (8 -> 16 -> 32 -> 64) + * by copying the counts into a wider array, once per promotion, when a count would not fit. + * Every count is checked before it is written, so no count ever wraps. + * + * Promotion never changes a count, and never narrows: `clearCounts` keeps the current width. + * Negative counts throw in every width, so promotion never changes what is accepted. + */ +class AutoCountsHistogram extends TypedArrayHistogram { + private tier = 0; + private maxCount = TIERS[0].maxCount; + + constructor( + lowestDiscernibleValue: number, + highestTrackableValue: number, + numberOfSignificantValueDigits: number + ) { + super( + TIERS[0].ctr, + lowestDiscernibleValue, + highestTrackableValue, + numberOfSignificantValueDigits + ); + } + + // The recording hot path: the fit check is inlined here, the rare cases go to the helpers. + incrementCountAtIndex(index: number) { + const newCount = this._counts[index] + 1; + if (newCount > this.maxCount) { + this.promoteFor(newCount); + } + this._counts[index] = newCount; + } + + addToCountAtIndex(index: number, value: number) { + const newCount = this._counts[index] + value; + if (newCount > this.maxCount || newCount < 0) { + this.checkCount(newCount); + } + this._counts[index] = newCount; + } + + setCountAtIndex(index: number, value: number) { + this.writeCount(index, value); + } + + /** Current counts width in bits (8, 16, 32 or 64). */ + get currentBitBucketSize(): number { + return TIERS[this.tier].bits; + } + + // A wider count is promoted to, not refused: only counts no width can hold throw here, + // before an auto-resizing histogram grows. + protected checkRecordedCount(count: number) { + if (count < 0) { + this.throwNegativeCount(count); + } + if (count > Number.MAX_SAFE_INTEGER) { + throw new Error(count + " would overflow integer count"); + } + } + + private writeCount(index: number, newCount: number) { + if (newCount > this.maxCount || newCount < 0) { + this.checkCount(newCount); + } + this._counts[index] = newCount; + } + + private checkCount(newCount: number) { + if (newCount > this.maxCount) { + this.promoteFor(newCount); + } else if (newCount < 0) { + this.throwNegativeCount(newCount); + } + } + + private throwNegativeCount(count: number): never { + throw new Error( + count + + " is a negative count, which the auto counts histogram cannot hold" + ); + } + + /** + * Moves the counts to the narrowest width able to hold `count`. + * The array is copied once, so a single promotion costs one pass over the counts. + */ + private promoteFor(count: number) { + if (count > Number.MAX_SAFE_INTEGER) { + throw new Error(count + " would overflow integer count"); + } + let target = this.tier; + while (count > TIERS[target].maxCount) { + target++; + } + const { ctr, maxCount } = TIERS[target]; + const wider = new ctr(this._counts.length); + wider.set(this._counts); + this._counts = wider; + this.arrayCtr = ctr; + this.tier = target; + this.maxCount = maxCount; + } + + copyCorrectedForCoordinatedOmission( + expectedIntervalBetweenValueSamples: number + ) { + const copy = new AutoCountsHistogram( + this.lowestDiscernibleValue, + this.highestTrackableValue, + this.numberOfSignificantValueDigits + ); + copy.addWhileCorrectingForCoordinatedOmission( + this, + expectedIntervalBetweenValueSamples + ); + return copy; + } + + toString() { + return `AutoCountsHistogram ${this.currentBitBucketSize}b ${JSON.stringify( + this, + null, + 2 + )}`; + } +} + +export default AutoCountsHistogram; diff --git a/src/Histogram.ts b/src/Histogram.ts index f8c4a3c..c9d4742 100644 --- a/src/Histogram.ts +++ b/src/Histogram.ts @@ -2,7 +2,7 @@ import { keepSignificantDigits } from "./formatters"; export const NO_TAG = "NO TAG"; -export type BitBucketSize = 8 | 16 | 32 | 64 | "packed"; +export type BitBucketSize = 8 | 16 | 32 | 64 | "packed" | "auto"; export interface HistogramSummary { p50: number; diff --git a/src/HistogramBuilder.ts b/src/HistogramBuilder.ts index e6f660e..23dd74c 100644 --- a/src/HistogramBuilder.ts +++ b/src/HistogramBuilder.ts @@ -52,6 +52,9 @@ export const defaultRequest: BuildRequest = { export const build = (request = defaultRequest): Histogram => { const parameters = Object.assign({}, defaultRequest, request); + if (parameters.bitBucketSize === "auto" && request.useWebAssembly) { + throw new Error("bitBucketSize 'auto' is not supported with WebAssembly"); + } if (request.useWebAssembly && webAssemblyAvailable) { return WasmHistogram.build(parameters); } diff --git a/src/JsHistogramFactory.ts b/src/JsHistogramFactory.ts index 4c3005c..4a0522a 100644 --- a/src/JsHistogramFactory.ts +++ b/src/JsHistogramFactory.ts @@ -4,6 +4,7 @@ import Int8Histogram from "./Int8Histogram"; import Int16Histogram from "./Int16Histogram"; import Int32Histogram from "./Int32Histogram"; import Float64Histogram from "./Float64Histogram"; +import AutoCountsHistogram from "./AutoCountsHistogram"; import JsHistogram from "./JsHistogram"; export interface JsHistogramConstructor { @@ -28,6 +29,8 @@ export function constructorFromBucketSize( return Int32Histogram; case 64: return Float64Histogram; + case "auto": + return AutoCountsHistogram; default: throw new Error("Incorrect parameter bitBucketSize"); } diff --git a/src/TypedArrayHistogram.ts b/src/TypedArrayHistogram.ts index c1c1974..f65a384 100644 --- a/src/TypedArrayHistogram.ts +++ b/src/TypedArrayHistogram.ts @@ -25,7 +25,7 @@ class TypedArrayHistogram extends JsHistogram { private readonly countMax: number; constructor( - private arrayCtr: new (size: number) => TypedArray, + protected arrayCtr: new (size: number) => TypedArray, lowestDiscernibleValue: number, highestTrackableValue: number, numberOfSignificantValueDigits: number @@ -66,13 +66,18 @@ class TypedArrayHistogram extends JsHistogram { // Checked before the base class resizes an auto-resizing histogram, so a rejected // count leaves the histogram's range untouched. Only reached on the out-of-range path. handleRecordException(count: number, value: number) { + this.checkRecordedCount(count); + super.handleRecordException(count, value); + } + + /** Throws if `count` can never be stored, whatever the bucket it goes to. */ + protected checkRecordedCount(count: number) { if (count > this.countMax) { this.throwCountOverflow(count); } if (count < this.countMin) { this.throwCountUnderflow(count); } - super.handleRecordException(count, value); } incrementCountAtIndex(index: number) { diff --git a/src/bench/counts-promotion.bench.ts b/src/bench/counts-promotion.bench.ts new file mode 100644 index 0000000..c96c24a --- /dev/null +++ b/src/bench/counts-promotion.bench.ts @@ -0,0 +1,111 @@ +import { build, BuildRequest, Histogram } from "../index"; + +// Latency-like samples (nanoseconds, 100us to 10ms) in a histogram that tracks up to +// 10 seconds. Fixed-seed PRNG so runs and branches see the same values. +const SAMPLE_COUNT = 1024; +const HIGHEST = 10_000_000_000; +const samples: number[] = (() => { + let seed = 42; + const next = () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; + }; + return Array.from( + { length: SAMPLE_COUNT }, + () => 100_000 + Math.floor(next() * 9_900_000) + ); +})(); + +const request = (bitBucketSize: unknown): BuildRequest => ({ + bitBucketSize: bitBucketSize as BuildRequest["bitBucketSize"], + lowestDiscernibleValue: 1, + highestTrackableValue: HIGHEST, + numberOfSignificantValueDigits: 3, +}); + +// On master "auto" is not a valid bitBucketSize, so its entries are skipped there. +const autoSupported = (() => { + try { + build(request("auto")); + return true; + } catch { + return false; + } +})(); + +const modes: Array<[string, unknown]> = [ + ["Int32Histogram", 32], + ["Float64Histogram", 64], +]; +if (autoSupported) { + modes.push(["AutoCountsHistogram", "auto"]); +} +// COUNTS_BENCH_ONLY=32,auto runs one variant per process, so the variants do not +// share call sites (and their type feedback) when measured. +const only = process.env.COUNTS_BENCH_ONLY?.split(","); +const selected = only + ? modes.filter(([, bitBucketSize]) => only.includes(String(bitBucketSize))) + : modes; + +// bench.compare needs two or more entries; a single variant runs on its own. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const runAll = (bench: any, benches: any[]) => + benches.length > 1 ? bench.compare(...benches) : benches[0].run(); + +// Fresh histogram per batch: the counts stay at the narrow width the data needs, +// and the cost of allocating the counts array is included (as in a Recorder interval). +test("Record 1024 samples into a fresh histogram", async ({ bench }) => { + const benches = selected.map(([name, bitBucketSize]) => + bench(name, () => { + const histogram = build(request(bitBucketSize)); + for (let i = 0; i < samples.length; i++) { + histogram.recordValue(samples[i]); + } + }) + ); + await runAll(bench, benches); +}); + +// Long-lived histogram: after warm-up the auto histogram has promoted to the width +// its counts need, so this measures the steady state. +test("Record 1024 samples into a long-lived histogram", async ({ bench }) => { + const histograms = selected.map(([name, bitBucketSize]) => ({ + name, + histogram: build(request(bitBucketSize)), + })); + const benches = histograms.map(({ name, histogram }) => + bench(name, () => { + for (let i = 0; i < samples.length; i++) { + histogram.recordValue(samples[i]); + } + }) + ); + await runAll(bench, benches); +}); + +// Percentile scans over a histogram whose counts are small (auto stays at 8 bits). +const filled = selected.map(([name, bitBucketSize]) => { + const histogram: Histogram = build(request(bitBucketSize)); + for (let i = 0; i < samples.length; i++) { + histogram.recordValue(samples[i]); + } + return { name, histogram }; +}); + +test("getValueAtPercentile(99)", async ({ bench }) => { + const benches = filled.map(({ name, histogram }) => + bench(name, () => { + histogram.getValueAtPercentile(99); + }) + ); + await runAll(bench, benches); +}); + +test("summary (percentiles, max, totalCount)", async ({ bench }) => { + const benches = filled.map(({ name, histogram }) => + bench(name, () => { + histogram.summary; + }) + ); + await runAll(bench, benches); +}); diff --git a/src/encoding.ts b/src/encoding.ts index 13e0d5c..f72ed51 100644 --- a/src/encoding.ts +++ b/src/encoding.ts @@ -7,7 +7,7 @@ */ import { JsHistogram } from "./JsHistogram"; import ByteBuffer from "./ByteBuffer"; -import Histogram from "./Histogram"; +import Histogram, { BitBucketSize } from "./Histogram"; import { WasmHistogram } from "./wasm"; import * as base64 from "./base64"; @@ -39,7 +39,7 @@ export async function decompress(data: Uint8Array): Promise { export const decodeFromCompressedBase64 = async ( base64String: string, - bitBucketSize: 8 | 16 | 32 | 64 | "packed" = 32, + bitBucketSize: BitBucketSize = 32, useWebAssembly: boolean = false, minBarForHighestTrackableValue: number = 0 ): Promise => { diff --git a/src/wasm/index.ts b/src/wasm/index.ts index 9410047..e9257d3 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -291,8 +291,12 @@ const defaultRequest: BuildRequest = { numberOfSignificantValueDigits: 3, }; -const remoteHistogramClassFor = (size?: BitBucketSize) => - size === "packed" ? "PackedHistogram" : `Histogram${size}`; +const remoteHistogramClassFor = (size?: BitBucketSize) => { + if (size === "auto") { + throw new Error("bitBucketSize 'auto' is not supported with WebAssembly"); + } + return size === "packed" ? "PackedHistogram" : `Histogram${size}`; +}; /** Map class name to the suffix used in the exported WASM function names */ function suffixFor(remoteHistogramClass: string): string { @@ -340,7 +344,7 @@ export class WasmHistogram implements Histogram { static decode( data: Uint8Array, - bitBucketSize: 8 | 16 | 32 | 64 | "packed" = 32, + bitBucketSize: BitBucketSize = 32, minBarForHighestTrackableValue: number = 0 ): Histogram { if (!webAssemblyReady()) {