Percentile Interpolation For Latency

Turn a sorted sample into p50 or p99 with linear interpolation between neighboring ranks, matching how perf metrics summarize latency.

JavascriptCli Tooling

Code

snippet
// Percentile from a sorted sample: linear interpolation blends the two
// neighbours around the fractional rank, the way perf metrics do
function percentile(sorted, p) {
  if (sorted.length === 0) throw new RangeError('empty sample');
  const rank = (p / 100) * (sorted.length - 1);
  const lower = Math.floor(rank);
  const fraction = rank - lower;
  const upper = Math.min(lower + 1, sorted.length - 1);
  return sorted[lower] + (sorted[upper] - sorted[lower]) * fraction;
}

const latencies = [12, 18, 24, 31, 45, 67, 89, 120, 240, 480].sort((a, b) => a - b);
console.log('p50:', percentile(latencies, 50).toFixed(1));
console.log('p95:', percentile(latencies, 95).toFixed(1));
console.log('p99:', percentile(latencies, 99).toFixed(1));

console.log('p0 is min:', percentile(latencies, 0) === latencies[0]);
console.log('p100 is max:', percentile(latencies, 100) === latencies[latencies.length - 1]);

// nearest-rank for comparison: the ceil(p/100 * n) th element, no blending
const nearest = latencies[Math.ceil(0.5 * latencies.length) - 1];
console.log('nearest-rank p50:', nearest, 'interpolated:', percentile(latencies, 50).toFixed(1));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

p50: 56.0
p95: 372.0
p99: 458.4
p0 is min: true
p100 is max: true
nearest-rank p50: 45 interpolated: 56.0

Order of operations

Percentile Interpolation For Latency is built around the functions rank and percentile.

A guard precedes the RangeError: bad state stops the flow there instead of continuing.

Points of care

  • The package manager never enters the picture for this snippet.
  • The guard sorted.length === 0 exits the flow through throw when its condition holds.

Putting it to use

Entry signature: const rank = (p / 100)

Output lines are prefixed (p50:, p95:, p99:), so the effect of each step announces itself.

Core lines

const latencies = [12, 18, 24, 31, 45, 67, 89, 120, 240, 480].sort((a, b) => a - b);
return sorted[lower] + (sorted[upper] - sorted[lower]) * fraction;
if (sorted.length === 0) throw new RangeError('empty sample');

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
Validation comes first — `RangeError` marks the failure at `sorted.length === 0`, before any partial work happens.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `rank`, `percentile` at load time.