Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 144 additions & 21 deletions assembly/Histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,30 @@ function horizontalSum(v: v128): u64 {
return <u64>i64x2.extract_lane(v, 0) + <u64>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<U>(p: usize): u64 {
let acc = widenSum<U>(v128.load(p));
acc = i64x2.add(acc, widenSum<U>(v128.load(p, 16)));
acc = i64x2.add(acc, widenSum<U>(v128.load(p, 32)));
acc = i64x2.add(acc, widenSum<U>(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<i32>(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 `<U>` cast). */
// @ts-ignore: decorator
@inline
Expand Down Expand Up @@ -661,21 +685,11 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
* value that all value entries in the histogram are either larger than or equivalent to.
*/
getValueAtPercentile(percentile: f64): u64 {
const requestedPercentile = min(percentile, <f64>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) * <f64>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 = <u64>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<f64>(fpCountAtPercentile)) {
return 0; // NaN percentile
}
const countAtPercentile = <u64>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
Expand All @@ -693,12 +707,8 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
const base = this.countsDataStart;
const step = lanes<U>() << 2;
while (i + step <= end) {
const p = base + (<usize>i << alignof<U>());
let acc = widenSum<U>(v128.load(p));
acc = i64x2.add(acc, widenSum<U>(v128.load(p, 16)));
acc = i64x2.add(acc, widenSum<U>(v128.load(p, 32)));
acc = i64x2.add(acc, widenSum<U>(v128.load(p, 48)));
const totalToBlockEnd = totalToCurrentIndex + horizontalSum(acc);
const totalToBlockEnd =
totalToCurrentIndex + sumBlock<U>(base + (<usize>i << alignof<U>()));
if (totalToBlockEnd >= countAtPercentile) break;
totalToCurrentIndex = totalToBlockEnd;
i += step;
Expand All @@ -718,12 +728,125 @@ export default class Histogram<T, U> extends AbstractHistogramBase<T, U> {
}
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<f64>(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<U>() << 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<T>()) {
if (i > 0 && i + step <= end) {
const totalToBlockEnd =
total +
<f64>sumBlock<U>(this.countsDataStart + (<usize>i << alignof<U>()));
if (totalToBlockEnd < unchecked(thresholds[unchecked(order[next])])) {
total = totalToBlockEnd;
i += step;
continue;
}
chunkEnd = i + step;
}
}
for (; i < chunkEnd; i++) {
total += <f64>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] = <f64>(
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, <f64>100), <f64>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) * <f64>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 (<u64>subBucketIndex) << (bucketIndex + this.unitMagnitude);
}
Expand Down
11 changes: 11 additions & 0 deletions assembly/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import ByteBuffer from "./ByteBuffer";
import { PackedArray } from "./packedarray/PackedArray";

export const UINT8ARRAY_ID = idof<Uint8Array>();
export const FLOAT64ARRAY_ID = idof<Float64Array>();

class HistogramAdapter<T, U> {
private _histogram!: Histogram<T, U>;
Expand Down Expand Up @@ -156,6 +157,10 @@ class HistogramAdapter<T, U> {
return <f64>this._histogram.getValueAtPercentile(percentile);
}

getValuesAtPercentiles(percentiles: Float64Array): Float64Array {
return this._histogram.getValuesAtPercentiles(percentiles);
}

outputPercentileDistribution(
percentileTicksPerHalfDistance: f64,
outputValueUnitScalingRatio: f64
Expand Down Expand Up @@ -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); }
Expand Down
30 changes: 22 additions & 8 deletions src/Histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
};
Expand Down
Loading
Loading