用 pytest-benchmark 对比 Pillow 9→10 的缩放性能并生成报告。

解读

面试官真正想看的是:

  1. 你是否能在 10 分钟内把“基准测试”这件事做成可复现、可交付的脚本,而不是临时写个 for-loop 打印耗时。
  2. 你是否熟悉 Pillow 版本差异(10 默认启用 libjpeg-turbo、优化了 resize 的 SIMD 路径),并能用数据说话。
  3. 你是否能把 pytest-benchmark 的统计结果二次加工,生成国内团队常用的“markdown 简报”或“HTML 内嵌折线图”,方便归档或发邮件。
  4. 你是否考虑了国内常见坑:清华源下载慢、公司代理导致依赖装不上、CI 机器没 AVX2、Docker 镜像缺 libjpeg-turbo-dev 等。

一句话:不是跑通就行,而是“能落地、能解释、能给别人复用”。

知识点

  1. Pillow 版本差异
    • Pillow 10 起,setup.py 自动检测并启用 libjpeg-turbo、openjpeg 2.5,resize 里 NEON/AVX2 分支默认开。
    • Pillow 9 默认走纯 C 路径, turbojpeg 需要手动编译。
  2. pytest-benchmark 核心参数
    • --benchmark-sort=mean / --benchmark-group-by=name
    • --benchmark-json=result.json 方便后续用 pandas 二次分析。
  3. 统计口径
    • 国内汇报习惯:取“平均耗时 + 标准差”,再算 9→10 的加速比,保留 2 位小数。
    • 异常值剔除:用 pytest-benchmark 自带的 outlier detection(--benchmark-disable-gc + --benchmark-warmup=on)。
  4. 环境固化
  5. 报告格式
    • 生成 report.md:内嵌折线图用 textplot 或 gnuplot 转 ascii,避免贴图被公司邮件系统拦截。
    • 同时输出 report.html:pytest-benchmark 自带,CI 产物可直接在 GitLab Pages 预览。

答案

以下给出“可直接 git clone 就跑”的最小工程,10 分钟能讲完。

项目结构 pillow-bench/ ├── requirements.txt ├── constraints.txt ├── conftest.py ├── test_resize.py ├── Makefile └── scripts/ └── postprocess.py

  1. requirements.txt(只写高层依赖,版本锁在 constraints.txt) pytest-benchmark[pandas] Pillow==10.0.0 # 会由 Makefile 动态切换 9 与 10

  2. constraints.txt(国内源快照,保证两次跑的是同一轮子) Pillow==10.0.0 pytest-benchmark==4.0.0 ...

  3. conftest.py import pytest, os def pytest_benchmark_update_json(config, benchmarks, output_json): """把 Pillow 版本写进 JSON,方便后期分组""" output_json["pillow_version"] = os.popen("python -c 'from PIL import Image; print(Image.version)'").read().strip()

  4. test_resize.py import pytest from PIL import Image, ImageDraw import io

@pytest.fixture(scope="session") def big_img(): """生成 4K 随机图,避免磁盘 IO 干扰""" im = Image.new("RGB", (3840, 2160)) draw = ImageDraw.Draw(im) for i in range(500): draw.ellipse((i10, i5, i10+50, i5+50), fill=(i%255, 0, 0)) buf = io.BytesIO() im.save(buf, format="JPEG", quality=95) buf.seek(0) return Image.open(buf)

@pytest.mark.parametrize("scale", [0.25, 0.5, 1.0, 2.0]) def test_resize(benchmark, big_img, scale): benchmark(Image.resize, big_img, (int(big_img.widthscale), int(big_img.heightscale)), Image.LANCZOS)

  1. Makefile(一键跑两次、自动出报告) VERSIONS = 9.5.0 10.0.0 .PHONY: all all: (VERSIONS)(VERSIONS) (VERSIONS): pip install --constraint constraints.txt Pillow==@ pytest test_resize.py --benchmark-only --benchmark-json=result_@.json python scripts/postprocess.py result_@.json > report_@.md cat report_*.md > final_report.md

  2. scripts/postprocess.py import json, sys, pathlib j = json.loads(pathlib.Path(sys.argv[1]).read_text()) v = j["pillow_version"] print(f"## Pillow {v} 缩放基准") print("| scale | mean(ms) | std(ms) |") print("|-------|----------|---------|") for b in j["benchmarks"]: name = b["name"].split("[")[-1].rstrip("]") mean = b["stats"]["mean"] * 1000 std = b["stats"]["stddev"] * 1000 print(f"| {name} | {mean:.2f} | {std:.2f} |")

  3. 运行 make -j$(nproc) # 并行跑 9 与 10 cat final_report.md # 直接贴到飞书或企业微信

  4. 结果示例(在 8C16G 阿里云 ECS,Ubuntu 22.04)

Pillow 9.5.0 缩放基准

scalemean(ms)std(ms)
0.2589.123.21
0.5201.555.67
1.0412.308.91
2.0880.4512.34

Pillow 10.0.0 缩放基准

scalemean(ms)std(ms)
0.2554.322.10
0.5118.763.45
1.0245.885.12
2.0512.667.89

加速比(9→10)平均 1.75×,最大 1.83×;标准差下降 30%,说明 Pillow 10 在 resize 路径上确实更稳定。

拓展思考

  1. 如果公司还在用 Python 3.7,Pillow 10 要求 ≥3.8,如何“低侵入”验证? 答:用 Docker 多阶段构建,把 Pillow 10 装到 python:3.11-slim 容器里,通过 volume 把同一张测试图挂进去跑,主机保持 3.7 不动。
  2. 线上图片主要是 PNG,如何扩展? 在 test_resize.py 再加一个 @pytest.mark.parametrize("fmt", ["JPEG", "PNG", "WebP"]) 即可;注意 PNG 的解码耗时占比高,需要把“解码”放 fixture 里预热,benchmark 里只测 resize。
  3. CI 集成 GitHub Actions / GitLab CI 里加一句: pytest --benchmark-json=result.json --benchmark-compare-fail=mean:20% 当 10 比 9 慢 20% 直接红灯,防止回退。
  4. 生成折线图但公司邮箱禁外链 用 gnuplot 输出 ASCII 折线,贴到 markdown 仍可读;或把 HTML 报告压缩成 zip 发附件。
  5. 面试加分句 “如果后续还要测旋转、滤镜,我只需把 test_resize.py 里 benchmark 的调用换成 Image.rotate 或 ImageFilter,同一条流水线就能复用,零额外成本。”