任务
先排序,再按最近秩取对应位置的值;样本不足时高位数会落在最大值上。
契约
- 输入:JSON 对象:{ latencies: number[] },单位毫秒
- 输出:JSON 对象:{ p50, p95, p99, mean }
样例
- 输入
{"latencies":[10,20,30,40,50,60,70,80,90,100]}-> 期望{"p50":50,"p95":100,"p99":100,"mean":55}。十个样本用最近秩计算时,p95 与 p99 都落在最大值上。 - 输入
{"latencies":[5,15,25,35,45,55,65,75,85,95,105,115,125,135,145,155,165,175,185,195]}-> 期望{"p50":95,"p95":185,"p99":195,"mean":100}。二十个样本下 p50 是第十个值(95),p95 是第十九个(185),p99 是最大值。
参考实现
function solve({ latencies }) {
const sorted = [...latencies].sort((a, b) => a - b);
const percentile = (p) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
const mean = +(sorted.reduce((a, b) => a + b, 0) / sorted.length).toFixed(2);
return { p50: percentile(50), p95: percentile(95), p99: percentile(99), mean };
}
为什么有效
均值会低估尾部的痛感。分位数回答“最慢的那批用户体验有多糟”,也是同行与 SLO 书写时依据的数值。
先排序,并使用最近秩而不是插值,这样分位数取到的是一个真实观测样本。