--durations 统计每个测试项从 fixture setup 到 teardown 的完整耗时(含 fixture 开销),默认不显示;设为正整数(如 --durations=5)输出最慢的 N 个,--durations=0 输出所有用例倒序列表,单位秒、精度毫秒。
pytest --durations 显示耗时的原理和默认行为
pytest 默认不展示用例执行时间,--durations 是一个内置参数,它不会改变测试执行逻辑,只在运行结束后统计并输出最慢的 N 个用例(默认 N=0,即不显示;设为正整数才生效)。它统计的是每个 test_* 函数从进入 pytest 的 fixture setup 到 teardown 结束的完整生命周期耗时,包含 fixture 开销,不是纯函数体执行时间。
-
--durations=5输出最慢的 5 个用例 -
--durations=0输出所有用例按耗时倒序排列 - 耗时单位是秒,精度到毫秒(如
0.123s) - 不支持按模块/类分组排序,只按单个函数粒度
为什么加了 --durations 却没看到耗时列表?
常见原因不是参数写错,而是触发条件没满足:
- 忘记指定数值:只写
--durations不带数字,等价于--durations=0,但 pytest 3.7+ 版本起已改为默认不输出(需显式写--durations=0或--durations=10) - 测试全部跳过(
pytest.skip())或全被过滤(-k匹配不到),导致无用例执行,自然无耗时统计 - 使用了
--tb=no或--quiet等抑制输出的选项,会连带隐藏--durations报告段落 - 在 CI 环境中 stdout 被重定向且未 flush,可能让最后一段输出丢失(可加
--capture=no排查)
如何把 --durations 结果导出到文件或配合 HTML 报告
pytest 自身不支持直接导出 --durations 到 JSON/CSV,但可通过组合方式落地:
- 重定向终端输出:
pytest --durations=10 --tb=short > durations.log 2>&1(注意 stderr 也要捕获) - 配合
pytest-html插件:它默认不展示耗时,但启用--html=report.html --self-contained-html后,可在报告底部“Test Durations”区域看到汇总(需插件 v3.2.0+) - 若需每个用例行内标耗时,得换方案:
pytest --durations=0 -v是最接近的 CLI 方式;更细粒度要靠自定义 hook,例如在pytest_runtest_makereport中记录report.duration并写入临时文件
耗时数据不准?可能是 fixture 或 setup_method 拖慢了统计
--durations 统计的是整个测试项(item)耗时,包括:
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
- 所有作用域 ≥ function 的 fixture(如
@pytest.fixture(scope="session")只算首次调用) - 类级
setup_method/teardown_method(如果用了 unittest 风格) -
pytest_generate_tests参数化生成阶段不计入,但每个生成出的用例单独计时
容易误判的点:
- 一个用例耗时 2.4s,但实际函数体只跑 0.1s → 很可能卡在某个
module级 fixture 的首次初始化(比如启动数据库连接) - 并发执行(
pytest-xdist)下,--durations仍按单进程视角统计,无法反映资源争抢导致的延迟 - Windows 上高精度计时受系统调度影响,误差可能达 ±10ms,别拿它做微秒级性能归因
真正要定位瓶颈,得配合 pytest --profile(需安装 pytest-profiling)或在关键路径加 time.perf_counter() 手动打点。