diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index 3ace11b..e96d3aa 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -65,6 +65,30 @@ function horizontalSum(v: v128): u64 { return i64x2.extract_lane(v, 0) + i64x2.extract_lane(v, 1); } +/** Sum of the 64 bytes of U-wide counts starting at p (may be unaligned). */ +// @ts-ignore: decorator +@inline +function sumBlock(p: usize): u64 { + let acc = widenSum(v128.load(p)); + acc = i64x2.add(acc, widenSum(v128.load(p, 16))); + acc = i64x2.add(acc, widenSum(v128.load(p, 32))); + acc = i64x2.add(acc, widenSum(v128.load(p, 48))); + return horizontalSum(acc); +} + +// Scratch state of getValuesAtPercentiles, kept across calls: the minimal +// runtime only reclaims memory on __collect, so per-call allocations would +// grow the heap of a long-lived module. +let percentileThresholds = new Float64Array(0); +const percentileOrder = new Array(0); + +/** Orders two positions of percentileOrder by their threshold. */ +function byThreshold(a: i32, b: i32): i32 { + const ta = unchecked(percentileThresholds[a]); + const tb = unchecked(percentileThresholds[b]); + return ta < tb ? -1 : ta > tb ? 1 : 0; +} + /** Lane-wise wrapping add of U-wide integers (same wrap semantics as the scalar `` cast). */ // @ts-ignore: decorator @inline @@ -661,21 +685,11 @@ export default class Histogram extends AbstractHistogramBase { * value that all value entries in the histogram are either larger than or equivalent to. */ getValueAtPercentile(percentile: f64): u64 { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = - (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const fpCountAtPercentile = this.countAtPercentile(percentile); + if (isNaN(fpCountAtPercentile)) { + return 0; // NaN percentile + } + const countAtPercentile = fpCountAtPercentile; // Index 0 holds the zero values and is the only index below the one of // minNonZeroValue that may hold a count; nothing is recorded past the @@ -693,12 +707,8 @@ export default class Histogram extends AbstractHistogramBase { const base = this.countsDataStart; const step = lanes() << 2; while (i + step <= end) { - const p = base + (i << alignof()); - let acc = widenSum(v128.load(p)); - acc = i64x2.add(acc, widenSum(v128.load(p, 16))); - acc = i64x2.add(acc, widenSum(v128.load(p, 32))); - acc = i64x2.add(acc, widenSum(v128.load(p, 48))); - const totalToBlockEnd = totalToCurrentIndex + horizontalSum(acc); + const totalToBlockEnd = + totalToCurrentIndex + sumBlock(base + (i << alignof())); if (totalToBlockEnd >= countAtPercentile) break; totalToCurrentIndex = totalToBlockEnd; i += step; @@ -718,12 +728,125 @@ export default class Histogram extends AbstractHistogramBase { } if (i >= end) return 0; } + return this.valueAtPercentileIndex(i, percentile); + } + + /** The value reported for a percentile whose count is reached at index i. */ + // @ts-ignore: decorator + @inline + private valueAtPercentileIndex(i: i32, percentile: f64): u64 { const valueAtIndex: u64 = this.valueFromIndex(i); return percentile === 0.0 ? this.lowestEquivalentValue(valueAtIndex) : this.highestEquivalentValue(valueAtIndex); } + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry of `percentiles` is replaced by what getValueAtPercentile + * returns for it, so the results are in the input order; the array is + * returned. The percentiles may be unsorted or repeated. The caller keeps + * ownership of the array: nothing is allocated per call. + */ + getValuesAtPercentiles(percentiles: Float64Array): Float64Array { + const count = percentiles.length; + if (percentileThresholds.length < count) { + percentileThresholds = new Float64Array(count); + } + const thresholds = percentileThresholds; + // Positions sorted by the count each one has to reach. A NaN threshold + // (NaN percentile) is left out and its entry becomes 0, as in + // getValueAtPercentile. + const order = percentileOrder; + order.length = 0; + for (let position = 0; position < count; position++) { + const threshold = this.countAtPercentile(unchecked(percentiles[position])); + if (isNaN(threshold)) { + unchecked((percentiles[position] = 0)); + continue; + } + unchecked((thresholds[position] = threshold)); + order.push(position); + } + const valid = order.length; + if (valid == 0) { + return percentiles; + } + order.sort(byThreshold); + + const step = lanes() << 2; // indexes per 64-byte block + const end = this.highestNonZeroCountsIndex() + 1; + const lowest = this.lowestNonZeroCountsIndex(); + let next = 0; // First entry of `order` not yet resolved + let total: f64 = 0; // Sum of the counts below index i + let i: i32 = 0; + while (next < valid && i < end) { + // Index 0 is a chunk of its own; the other chunks are one index or, on + // flat storage, one 64-byte block that the next threshold does not reach. + let chunkEnd: i32 = i + 1; + if (isFlatStorage()) { + if (i > 0 && i + step <= end) { + const totalToBlockEnd = + total + + sumBlock(this.countsDataStart + (i << alignof())); + if (totalToBlockEnd < unchecked(thresholds[unchecked(order[next])])) { + total = totalToBlockEnd; + i += step; + continue; + } + chunkEnd = i + step; + } + } + for (; i < chunkEnd; i++) { + total += this.getCountAtIndex(i); + while (next < valid && total >= unchecked(thresholds[unchecked(order[next])])) { + // Each position is resolved once, so its percentile is read before + // the result overwrites it. + const position = unchecked(order[next]); + unchecked( + (percentiles[position] = ( + this.valueAtPercentileIndex(i, unchecked(percentiles[position])) + )) + ); + next++; + } + if (next == valid) { + break; + } + } + if (chunkEnd == 1) i = lowest; // index 0 is followed by the lowest non-zero index + } + // Thresholds never reached (an empty histogram, or a count above the + // recorded total that cannot happen) leave their entry at 0. + for (; next < valid; next++) { + unchecked((percentiles[unchecked(order[next])] = 0)); + } + return percentiles; + } + + /** + * Number of recorded values a percentile must reach, rounded as + * getValueAtPercentile has always rounded it. + */ + countAtPercentile(percentile: f64): f64 { + // Clamp to [0, 100]; a NaN percentile stays NaN + const requestedPercentile = max(min(percentile, 100), 0); + + // round count up to nearest integer, to ensure that the largest value that the requested percentile + // of overall recorded values is actually included. However, this must be done with care: + // + // First, Compute fp value for count at the requested percentile. Note that fp result end up + // being 1 ulp larger than the correct integer count for this percentile: + const fpCountAtPercentile = + (requestedPercentile / 100.0) * this.totalCount; + // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from + // making us skip a count: + return max( + ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up + 1 // Make sure we at least reach the first recorded entry + ); + } + valueFromIndexes(bucketIndex: i32, subBucketIndex: i32): u64 { return (subBucketIndex) << (bucketIndex + this.unitMagnitude); } diff --git a/assembly/index.ts b/assembly/index.ts index bb8f252..7fa7047 100644 --- a/assembly/index.ts +++ b/assembly/index.ts @@ -18,6 +18,7 @@ import ByteBuffer from "./ByteBuffer"; import { PackedArray } from "./packedarray/PackedArray"; export const UINT8ARRAY_ID = idof(); +export const FLOAT64ARRAY_ID = idof(); class HistogramAdapter { private _histogram!: Histogram; @@ -156,6 +157,10 @@ class HistogramAdapter { return this._histogram.getValueAtPercentile(percentile); } + getValuesAtPercentiles(percentiles: Float64Array): Float64Array { + return this._histogram.getValuesAtPercentiles(percentiles); + } + outputPercentileDistribution( percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64 @@ -447,6 +452,12 @@ export function getValueAtPercentile32(h: Histogram32, percentile: f64): f64 { r export function getValueAtPercentile64(h: Histogram64, percentile: f64): f64 { return h.getValueAtPercentile(percentile); } export function getValueAtPercentilePacked(h: PackedHistogram, percentile: f64): f64 { return h.getValueAtPercentile(percentile); } +export function getValuesAtPercentiles8(h: Histogram8, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles16(h: Histogram16, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles32(h: Histogram32, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles64(h: Histogram64, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentilesPacked(h: PackedHistogram, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } + export function outputPercentileDistribution8(h: Histogram8, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } export function outputPercentileDistribution16(h: Histogram16, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } export function outputPercentileDistribution32(h: Histogram32, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } diff --git a/src/Histogram.ts b/src/Histogram.ts index b448861..f8c4a3c 100644 --- a/src/Histogram.ts +++ b/src/Histogram.ts @@ -97,6 +97,17 @@ export default interface Histogram { */ getValueAtPercentile(percentile: number): number; + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry is what {@link getValueAtPercentile} returns for the same + * percentile. Results are in the argument order; the percentiles may be + * unsorted or repeated, and no argument returns an empty array. + * + * @param percentiles The percentiles for which to return the associated values + * @return The values, one per requested percentile + */ + getValuesAtPercentiles(...percentiles: number[]): number[]; + /** * Produce textual representation of the value distribution of histogram data by percentile. The distribution is * output with exponentially increasing resolution, with each exponentially decreasing half-distance containing @@ -240,15 +251,18 @@ export interface HistogramConstructor { export const toSummary = (histogram: Histogram): HistogramSummary => { const { totalCount, maxValue, numberOfSignificantValueDigits } = histogram; const round = keepSignificantDigits(numberOfSignificantValueDigits); + const [p50, p75, p90, p97_5, p99, p99_9, p99_99, p99_999] = histogram + .getValuesAtPercentiles(50, 75, 90, 97.5, 99, 99.9, 99.99, 99.999) + .map((value) => round(value)); return { - p50: round(histogram.getValueAtPercentile(50)), - p75: round(histogram.getValueAtPercentile(75)), - p90: round(histogram.getValueAtPercentile(90)), - p97_5: round(histogram.getValueAtPercentile(97.5)), - p99: round(histogram.getValueAtPercentile(99)), - p99_9: round(histogram.getValueAtPercentile(99.9)), - p99_99: round(histogram.getValueAtPercentile(99.99)), - p99_999: round(histogram.getValueAtPercentile(99.999)), + p50, + p75, + p90, + p97_5, + p99, + p99_9, + p99_99, + p99_999, max: maxValue, totalCount, }; diff --git a/src/Histogram.valuesAtPercentiles.spec.ts b/src/Histogram.valuesAtPercentiles.spec.ts new file mode 100644 index 0000000..673e229 --- /dev/null +++ b/src/Histogram.valuesAtPercentiles.spec.ts @@ -0,0 +1,264 @@ +/* + * 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 * as fc from "fast-check"; +import * as hdr from "./index"; +import { initWebAssembly } from "./wasm"; +import Histogram from "./Histogram"; +import { keepSignificantDigits } from "./formatters"; + +const runFromStryker = __dirname.includes("stryker"); +const runnerOptions = { + numRuns: runFromStryker ? 10 : 300, + verbose: true, +}; + +const numberOfSignificantValueDigits = 3; + +const implementations: { name: string; build: () => Histogram }[] = [ + { + name: "JS 32-bit", + build: () => + hdr.build({ bitBucketSize: 32, numberOfSignificantValueDigits }), + }, + { + name: "JS packed", + build: () => + hdr.build({ bitBucketSize: "packed", numberOfSignificantValueDigits }), + }, + { + name: "Float64", + build: () => + new hdr.Float64Histogram( + 1, + 1_000_000_000, + numberOfSignificantValueDigits + ), + }, + { + name: "WASM 32-bit", + build: () => + hdr.build({ + bitBucketSize: 32, + numberOfSignificantValueDigits, + useWebAssembly: true, + }), + }, + { + name: "WASM packed", + build: () => + hdr.build({ + bitBucketSize: "packed", + numberOfSignificantValueDigits, + useWebAssembly: true, + }), + }, +]; + +// Values spread over a wide range, so the counts have long empty stretches +// (the bounded scan and the block skipping both get exercised). +const recordsArb = fc.array( + fc.record({ + value: fc.integer({ min: 0, max: 5_000_000 }), + count: fc.integer({ min: 1, max: 50 }), + }), + { maxLength: 300 } +); + +// Unsorted, possibly repeated, including the edges (0, 100, above 100, +// negative, infinite). +const percentilesArb = fc.array( + fc.oneof( + fc.constantFrom( + 0, + 50, + 75, + 97.5, + 99, + 99.9, + 99.99, + 99.999, + 100, + 150, + -1, + -Infinity, + Infinity + ), + fc.double({ min: -10, max: 110, noNaN: true }) + ), + { maxLength: 20 } +); + +type Record = { value: number; count: number }; + +const fill = (histogram: Histogram, records: Record[]) => { + records.forEach(({ value, count }) => + histogram.recordValueWithCount(value, count) + ); + return histogram; +}; + +describe.each(implementations)( + "getValuesAtPercentiles on $name", + ({ build, name }) => { + beforeAll(initWebAssembly); + + it("should return 0 for NaN when the unit magnitude is not 0", () => { + // given + const useWebAssembly = name.startsWith("WASM"); + const bitBucketSize = name.endsWith("packed") ? "packed" : 32; + const histogram = hdr.build({ + bitBucketSize, + useWebAssembly, + lowestDiscernibleValue: 1000, + highestTrackableValue: 1_000_000, + numberOfSignificantValueDigits, + }); + histogram.recordValue(5000); + // when + const single = histogram.getValueAtPercentile(NaN); + const values = histogram.getValuesAtPercentiles(NaN, 50); + // then + expect(single).toBe(0); + expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); + histogram.destroy(); + }); + + it.runIf(name.startsWith("WASM"))("should throw after destroy", () => { + // given + const histogram = fill(build(), [{ value: 42, count: 3 }]); + histogram.destroy(); + // when + const call = () => histogram.getValuesAtPercentiles(50); + // then + expect(call).toThrow(); + }); + + it("should match getValueAtPercentile for each requested percentile", () => { + fc.assert( + fc.property(recordsArb, percentilesArb, (records, percentiles) => { + const histogram = fill(build(), records); + try { + const expected = percentiles.map((p) => + histogram.getValueAtPercentile(p) + ); + expect(histogram.getValuesAtPercentiles(...percentiles)).toEqual( + expected + ); + } finally { + histogram.destroy(); + } + }), + runnerOptions + ); + }); + + it("should return an empty array when called without percentiles", () => { + // given + const histogram = fill(build(), [{ value: 42, count: 3 }]); + // when + const values = histogram.getValuesAtPercentiles(); + // then + expect(values).toEqual([]); + histogram.destroy(); + }); + + it("should return 0 for every percentile of an empty histogram", () => { + // given + const histogram = build(); + // when + const values = histogram.getValuesAtPercentiles(0, 50, 99.9, 100); + // then + expect(values).toEqual([0, 0, 0, 0]); + histogram.destroy(); + }); + + it("should keep the argument order for unsorted and repeated percentiles", () => { + // given + const histogram = fill( + build(), + Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) + ); + // when + const values = histogram.getValuesAtPercentiles(99, 50, 99, 0, 100); + // then + expect(values).toEqual([99, 50, 99, 1, 100]); + histogram.destroy(); + }); + + it("should truncate percentiles above 100 to 100", () => { + // given + const histogram = fill(build(), [ + { value: 10, count: 1 }, + { value: 1000, count: 1 }, + ]); + // when + const [above, top] = histogram.getValuesAtPercentiles(150, 100); + // then + expect(above).toBe(top); + expect(top).toBe(histogram.getValueAtPercentile(100)); + histogram.destroy(); + }); + + it("should return 0 for a NaN percentile and still answer the others", () => { + // given + const histogram = fill(build(), [{ value: 50, count: 10 }]); + // when + const values = histogram.getValuesAtPercentiles(NaN, 50); + // then + expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); + histogram.destroy(); + }); + + it("should treat negative and -Infinity percentiles as 0", () => { + // given + const histogram = fill( + build(), + Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) + ); + // when + const values = histogram.getValuesAtPercentiles( + -Infinity, + 50, + -1, + Infinity + ); + // then + expect(histogram.getValueAtPercentile(-1)).toBe(1); + expect(histogram.getValueAtPercentile(-Infinity)).toBe(1); + expect(values).toEqual([1, 50, 1, 100]); + histogram.destroy(); + }); + + it("should compute summary values equal to the per-percentile values, rounded", () => { + fc.assert( + fc.property(recordsArb, (records) => { + const histogram = fill(build(), records); + try { + const round = keepSignificantDigits(numberOfSignificantValueDigits); + const at = (p: number) => round(histogram.getValueAtPercentile(p)); + expect(histogram.summary).toEqual({ + p50: at(50), + p75: at(75), + p90: at(90), + p97_5: at(97.5), + p99: at(99), + p99_9: at(99.9), + p99_99: at(99.99), + p99_999: at(99.999), + max: histogram.maxValue, + totalCount: histogram.totalCount, + }); + } finally { + histogram.destroy(); + } + }), + runnerOptions + ); + }); + } +); diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index ab3148e..f6c55a3 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -496,20 +496,7 @@ export abstract class JsHistogram implements Histogram { * value that all value entries in the histogram are either larger than or equivalent to. */ getValueAtPercentile(percentile: number) { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const countAtPercentile = this.countAtPercentile(percentile); // Index 0 holds the zero values and is the only index below the one of // minNonZeroValue that may hold a count; nothing is recorded past the @@ -521,15 +508,85 @@ export abstract class JsHistogram implements Histogram { for (let i = 0; i <= lastIndex; i = i === 0 ? firstNonZeroIndex : i + 1) { totalToCurrentIndex += this.getCountAtIndex(i); if (totalToCurrentIndex >= countAtPercentile) { - const valueAtIndex = this.valueFromIndex(i); - return percentile === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex); + return this.valueAtPercentileIndex(i, percentile); } } return 0; } + /** The value reported for a percentile whose count is reached at index i. */ + protected valueAtPercentileIndex(i: number, percentile: number): number { + const valueAtIndex = this.valueFromIndex(i); + return percentile === 0.0 + ? this.lowestEquivalentValue(valueAtIndex) + : this.highestEquivalentValue(valueAtIndex); + } + + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry is what {@link getValueAtPercentile} returns for the same + * percentile; results are in the argument order. The percentiles may be + * unsorted or repeated. + * + * @param percentiles The percentiles for which to return the associated values + * @return The values, one per requested percentile + */ + getValuesAtPercentiles(...percentiles: number[]): number[] { + const results = new Array(percentiles.length).fill(0); + const thresholds = percentiles.map((p) => this.countAtPercentile(p)); + // Requested positions sorted by the count each one has to reach. NaN + // percentiles stay at 0, as getValueAtPercentile returns for them. + const order = thresholds + .map((_, position) => position) + .filter((position) => !Number.isNaN(thresholds[position])) + .sort((a, b) => thresholds[a] - thresholds[b]); + + const lastIndex = this.highestNonZeroCountsIndex(); + let next = 0; // First entry of `order` not yet resolved + let totalToCurrentIndex = 0; + for ( + let i = this.nextNonZeroIndexInRange(0, lastIndex); + next < order.length && i >= 0; + i = this.nextNonZeroIndexInRange(i + 1, lastIndex) + ) { + totalToCurrentIndex += this.getCountAtIndex(i); + while ( + next < order.length && + totalToCurrentIndex >= thresholds[order[next]] + ) { + const position = order[next]; + results[position] = this.valueAtPercentileIndex( + i, + percentiles[position] + ); + next++; + } + } + return results; + } + + /** + * Number of recorded values a percentile must reach, rounded as + * getValueAtPercentile has always rounded it. + */ + protected countAtPercentile(percentile: number): number { + // Clamp to [0, 100]; a NaN percentile stays NaN + const requestedPercentile = max(min(percentile, 100), 0); + + // round count up to nearest integer, to ensure that the largest value that the requested percentile + // of overall recorded values is actually included. However, this must be done with care: + // + // First, Compute fp value for count at the requested percentile. Note that fp result end up + // being 1 ulp larger than the correct integer count for this percentile: + const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; + // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from + // making us skip a count: + return max( + ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up + 1 // Make sure we at least reach the first recorded entry + ); + } + valueFromIndexes(bucketIndex: number, subBucketIndex: number) { return subBucketIndex * pow(2, bucketIndex + this.unitMagnitude); } diff --git a/src/PackedHistogram.ts b/src/PackedHistogram.ts index 6dea40a..c19ecff 100644 --- a/src/PackedHistogram.ts +++ b/src/PackedHistogram.ts @@ -7,9 +7,6 @@ */ import JsHistogram from "./JsHistogram"; import { PackedArray } from "./packedarray/PackedArray"; -import ulp from "./ulp"; - -const { ceil, max, min } = Math; /** *

A High Dynamic Range (HDR) Histogram that uses a packed internal representation

*

@@ -91,20 +88,7 @@ class PackedHistogram extends JsHistogram { * whole counts array. */ getValueAtPercentile(percentile: number) { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const countAtPercentile = this.countAtPercentile(percentile); let totalToCurrentIndex = 0; for ( @@ -114,10 +98,7 @@ class PackedHistogram extends JsHistogram { ) { totalToCurrentIndex += this.getCountAtIndex(i); if (totalToCurrentIndex >= countAtPercentile) { - const valueAtIndex = this.valueFromIndex(i); - return percentile === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex); + return this.valueAtPercentileIndex(i, percentile); } } return 0; diff --git a/src/wasm/index.ts b/src/wasm/index.ts index b32a01f..08d6bba 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -3,7 +3,7 @@ import Histogram, { NO_TAG, BitBucketSize, toSummary, - HistogramSummary + HistogramSummary, } from "../Histogram"; import * as base64 from "../base64"; import { inflate } from "../JsHistogram.encoding"; @@ -29,6 +29,7 @@ let wasm: any = undefined; // Cached at first decode call to avoid re-reading a getter on every array creation let cachedUint8ArrayId: number = 0; +let cachedFloat64ArrayId: number = 0; // Per-suffix function tables — built once per histogram type, shared by all instances. // Avoids the 25+ property lookups that would otherwise happen in every constructor. @@ -59,6 +60,7 @@ interface WasmFns { expectedInterval: number ) => void; getValueAtPercentile: (ptr: number, percentile: number) => number; + getValuesAtPercentiles: (ptr: number, percentiles: number) => number; outputPercentileDistribution: ( ptr: number, ticksPerHalfDistance: number, @@ -85,7 +87,8 @@ const COLLECT_INTERVAL = 1; function buildWasmFns(s: string): WasmFns { return { - getNumberOfSignificantValueDigits: wasm[`getNumberOfSignificantValueDigits${s}`], + getNumberOfSignificantValueDigits: + wasm[`getNumberOfSignificantValueDigits${s}`], getAutoResize: wasm[`getAutoResize${s}`], setAutoResize: wasm[`setAutoResize${s}`], getHighestTrackableValue: wasm[`getHighestTrackableValue${s}`], @@ -105,13 +108,17 @@ function buildWasmFns(s: string): WasmFns { getNonZeroCounts: wasm[`getNonZeroCounts${s}`], recordValue: wasm[`recordValue${s}`], recordValueWithCount: wasm[`recordValueWithCount${s}`], - recordValueWithExpectedInterval: wasm[`recordValueWithExpectedInterval${s}`], + recordValueWithExpectedInterval: + wasm[`recordValueWithExpectedInterval${s}`], getValueAtPercentile: wasm[`getValueAtPercentile${s}`], + getValuesAtPercentiles: wasm[`getValuesAtPercentiles${s}`], outputPercentileDistribution: wasm[`outputPercentileDistribution${s}`], encode: wasm[`encode${s}`], reset: wasm[`reset${s}`], - addWhileCorrectingForCoordinatedOmission: wasm[`addWhileCorrectingForCoordinatedOmission${s}`], - copyCorrectedForCoordinatedOmission: wasm[`copyCorrectedForCoordinatedOmission${s}`], + addWhileCorrectingForCoordinatedOmission: + wasm[`addWhileCorrectingForCoordinatedOmission${s}`], + copyCorrectedForCoordinatedOmission: + wasm[`copyCorrectedForCoordinatedOmission${s}`], }; } @@ -132,11 +139,9 @@ const wasmImports = { lineNumber: number, columnNumber: number ) { - throw new Error( - `Abort in WebAssembly at ${lineNumber}:${columnNumber}` - ); - } - } + throw new Error(`Abort in WebAssembly at ${lineNumber}:${columnNumber}`); + }, + }, }; // @ts-ignore @@ -184,7 +189,11 @@ function getFloat64Array(ptr: number): Float64Array { const U32 = new Uint32Array(wasm.memory.buffer); const dataStart = U32[(ptr + 4) >>> 2]; const byteLength = U32[(ptr + 8) >>> 2]; - return new Float64Array(wasm.memory.buffer, dataStart, byteLength / 8).slice(); + return new Float64Array( + wasm.memory.buffer, + dataStart, + byteLength / 8 + ).slice(); } /** @@ -203,23 +212,75 @@ function newUint8Array(data: Uint8Array): number { // Allocate underlying ArrayBuffer (id=1) and pin it during construction const bufPtr = wasm.__pin(wasm.__new(length, 1)); new Uint8Array(wasm.memory.buffer).set(data, bufPtr); - // Allocate the Uint8Array view (12-byte ArrayBufferView struct) and pin it - // so it stays alive through the GC cycles triggered by the decode allocation storm. - const viewPtr = wasm.__pin(wasm.__new(12, cachedUint8ArrayId)); + return newArrayBufferView(cachedUint8ArrayId, bufPtr, length); +} + +/** + * Allocates a pinned 12-byte ArrayBufferView of class `id` over the buffer + * at bufPtr, and releases the construction pin of that buffer. The view + * stays alive through the GC cycles triggered by later allocations until + * the caller unpins it. + */ +function newArrayBufferView( + id: number, + bufPtr: number, + byteLength: number +): number { + const viewPtr = wasm.__pin(wasm.__new(12, id)); const U32 = new Uint32Array(wasm.memory.buffer); U32[viewPtr >>> 2] = bufPtr; // buffer ref U32[(viewPtr + 4) >>> 2] = bufPtr; // dataStart - U32[(viewPtr + 8) >>> 2] = length; // byteLength + U32[(viewPtr + 8) >>> 2] = byteLength; // byteLength wasm.__unpin(bufPtr); return viewPtr; } +function float64ArrayId(): number { + if (!cachedFloat64ArrayId) { + cachedFloat64ArrayId = + typeof wasm.FLOAT64ARRAY_ID === "number" + ? wasm.FLOAT64ARRAY_ID + : (wasm.FLOAT64ARRAY_ID as any).value; + } + return cachedFloat64ArrayId; +} + +// Scratch Float64Array shared by the calls that pass a batch of numbers to +// WASM. A fresh array per call would never be freed: the minimal (tcms) +// runtime only reclaims memory on __collect, so per-call allocations would +// grow the wasm heap of a long-lived module. The view is pinned once and +// grown only when a larger batch arrives; its byteLength is set on each call. +let scratchFloat64View = 0; +let scratchFloat64Capacity = 0; // in elements + +/** + * Copies `values` into the scratch Float64Array and returns its (pinned, + * reused) view pointer. Memory views are taken after any allocation, as the + * wasm memory may have grown. + */ +function fillScratchFloat64Array(values: ArrayLike): number { + const length = values.length; + if (!scratchFloat64View || length > scratchFloat64Capacity) { + const capacity = Math.max(length, scratchFloat64Capacity * 2, 256); + const bufPtr = wasm.__pin(wasm.__new(capacity * 8, 1)); + const viewPtr = newArrayBufferView(float64ArrayId(), bufPtr, capacity * 8); + if (scratchFloat64View) wasm.__unpin(scratchFloat64View); + scratchFloat64View = viewPtr; + scratchFloat64Capacity = capacity; + } + const U32 = new Uint32Array(wasm.memory.buffer); + const dataStart = U32[(scratchFloat64View + 4) >>> 2]; + new Float64Array(wasm.memory.buffer, dataStart, length).set(values); + U32[(scratchFloat64View + 8) >>> 2] = length * 8; // byteLength + return scratchFloat64View; +} + const defaultRequest: BuildRequest = { bitBucketSize: 32, autoResize: true, lowestDiscernibleValue: 1, highestTrackableValue: 2, - numberOfSignificantValueDigits: 3 + numberOfSignificantValueDigits: 3, }; const remoteHistogramClassFor = (size?: BitBucketSize) => @@ -238,7 +299,10 @@ export class WasmHistogram implements Histogram { private _suffix: string; private _fns: WasmFns; - constructor(wasmPtr: number, private _remoteHistogramClass: string) { + constructor( + wasmPtr: number, + private _remoteHistogramClass: string + ) { this.tag = NO_TAG; this._suffix = suffixFor(_remoteHistogramClass); this._fns = getWasmFns(this._suffix); @@ -390,6 +454,19 @@ export class WasmHistogram implements Histogram { return this._fns.getValueAtPercentile(this._ptr, percentile); } + getValuesAtPercentiles(...percentiles: number[]): number[] { + if (this._ptr === 0) { + throw new Error("Cannot use a destroyed histogram"); + } + if (percentiles.length === 0) { + return []; + } + // The WASM side overwrites the scratch array with the values, in place + const viewPtr = fillScratchFloat64Array(percentiles); + this._fns.getValuesAtPercentiles(this._ptr, viewPtr); + return Array.from(getFloat64Array(viewPtr)); + } + outputPercentileDistribution( percentileTicksPerHalfDistance = 5, outputValueUnitScalingRatio = 1, @@ -460,9 +537,7 @@ export class WasmHistogram implements Histogram { add(otherHistogram: WasmHistogram): void { if (!(otherHistogram instanceof WasmHistogram)) { - throw new Error( - "Cannot add a regular JS histogram to a WASM histogram" - ); + throw new Error("Cannot add a regular JS histogram to a WASM histogram"); } wasm[`addHistogram${otherHistogram._suffix}to${this._suffix}`]( this._ptr,