如何为 pytest-benchmark 统计 P99 延迟?

解读

国内大厂(阿里、字节、美团)在面 FastAPI 接口性能岗位时,常把“你会看 P99 吗?”作为分水岭。
pytest-benchmark 默认只给出 min/max/mean/std,不直接吐 P99,候选人如果只会读控制台,就会被追问“线上告警阈值怎么定?”、“压测报告怎么给 SRE?”
因此,考点不是“跑个 benchmark”,而是“在 Python 测试体系里拿到准确且可复现的 P99,并集成到 CI”。
面试官期待听到:

  1. 知道 pytest-benchmark 的 stats 对象里藏着完整耗时数组;
  2. 会用 numpy 或 statistics 算分位,且不踩“排序后切片”性能坑;
  3. 能把结果落到 JSON,供 GitLab-CI 做性能门禁;
  4. 知道异步代码的 benchmark 陷阱(事件循环预热、uvloop 差异);
  5. 最终给出一条可拷贝的命令,让 SRE 复现。

知识点

  • pytest-benchmark 的 BenchmarkFixture 与 BenchmarkSession 对象
  • numpy.percentile / nanpercentile 的 interpolation 参数
  • 异步接口在 pytest-benchmark 中的两种写法:async 包装与 loop.run_until_complete
  • 预热(warmup)与重复次数(rounds)对尾延迟的影响
  • CI 门禁:将 benchmark.json 上传到内部性能平台,P99 超 50 ms 即阻断合并
  • 国内常见误区:把 throughput 当唯一指标,忽视长尾请求对用户体验的影响

答案

  1. 安装依赖
    pip install pytest-benchmark numpy

  2. 在 tests/ 目录下新建 test_p99.py

import numpy as np
from fastapi.testclient import TestClient
from myapp import app   # 你的 FastAPI 实例

client = TestClient(app)

def test_read_main(benchmark):
    # 让 benchmark 收集所有耗时
    result = benchmark.pedantic(
        target=lambda: client.get("/api/v1/item/123"),
        rounds=1000,      # 生产环境可调到 5k~10k
        iterations=1,
        warmup_rounds=3   # 预热,避免冷启动
    )
    # 取出原始耗时列表(单位秒)
    timings = result["stats"]["data"]
    p99 = np.percentile(timings, 99, interpolation="linear")
    # 控制台打印,方便本地调试
    print(f"\nP99 latency: {p99*1000:.2f} ms")
    # 写进 benchmark 自带的 extra_info,CI 会落盘
    benchmark.extra_info["p99_ms"] = round(p99 * 1000, 2)
    # 断言门禁:P99 必须 < 50 ms
    assert p99 < 0.05, f"P99 {p99*1000:.2f} ms 超过 50 ms 红线"
  1. 运行并生成报告
    pytest tests/test_p99.py --benchmark-json=report.json -q
    执行结束后,report.json 里会多出
    "extra_info": {"p99_ms": 42.13}

  2. GitLab-CI 片段(.gitlab-ci.yml)

performance:
  stage: test
  image: python:3.11-slim
  script:
    - pip install -r requirements.txt
    - pytest tests/test_p99.py --benchmark-json=report.json
    - export P99=$(cat report.json | jq '.benchmarks[0].extra_info.p99_ms')
    - '[ "$(echo "$P99 < 50" | bc)" -eq 1 ] || exit 1'
  only:
    - merge_requests
  1. 异步视图补充
    如果接口是 async,需要把 client 换成 httpx.AsyncClient,并用 asyncio.run 包一层:
import asyncio
import httpx

async def req():
    async with httpx.AsyncClient(app=app, base_url="http://test") as ac:
        r = await ac.get("/api/v1/item/123")
        return r.status_code

def test_async_p99(benchmark):
    benchmark.pedantic(
        target=lambda: asyncio.run(req()),
        rounds=1000, warmup_rounds=3
    )
    timings = benchmark.stats.data
    p99 = np.percentile(timings, 99)
    assert p99 < 0.05

至此,本地、CI、SRE 三线都能拿到同一份 P99 数据,满足国内互联网交付规范。

拓展思考

  • 如果接口依赖 Redis/MySQL,P99 会被尾部网络抖动放大,需在 benchmark 里 mock 外部 IO,或把“外部耗时”单独拆表,避免把框架本身的延迟误判为慢。
  • 当 rounds 过大导致测试机 CPU 打满,P99 反而失真,可在 nightly 流水线里用 4 核独占容器,并把 rounds 降到 95% 置信区间所需最小值(benchmark 自动计算)。
  • 对超大型微服务集群,单实例 P99 不足以评估容量,需要把 pytest-benchmark 数据推到 Prometheus,再聚合 instance 维度,得到“集群 P99”,这是国内 SRE 团队常用的“压测→监控”闭环。