← 中文资源

简体中文版本

分位数线性插值算延迟

对排序后的样本按 小数秩 在相邻两值之间线性插值,得到 p50/p95/p99 这类延迟指标;p0 与 p100 精确落在最小与最大值上,近邻秩口径可对照。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

活动部件是函数 rank、percentile。 失败是响亮的:RangeError 在守卫分支上直接中止当前操作,不做降级。

使用要点

  • 守卫 sorted.length === 0 成立时借助提前的 throw 直接离开。
  • 演示输出是带标签的(p50:、p95:、p99:),每个操作都会留下自己的一行标注。

常见问题

前置条件不满足时如何报错?

校验先行——RangeError 标记失败(位于 sorted.length === 0),不会先做一半再失败。

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 rank、percentile。

入口签名:const rank = (p / 100)

核心语句

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');

代码示例

// 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));