本文目录导读:

是的,Pytest-Benchmark 的结果可以可视化,它提供多种可视化方式,从简单的控制台输出到生成图表,以下是主要的可视化方法:
控制台表格输出(默认)
运行测试后自动生成格式化的表格:
pytest test_benchmark.py
输出示例:
---------------------------------------------------------------------------------------------------------------
Name (time in ns) Min Max Mean StdDev Median IQR Outliers OPS (Kops/s)
---------------------------------------------------------------------------------------------------------------
test_python_sort 1,200 1,500 1,300 100 1,250 120 10;5 769.23
test_custom_sort 1,500 2,000 1,700 150 1,650 130 5;2 588.24
---------------------------------------------------------------------------------------------------------------
生成可视化图表
安装依赖
pip install pytest-benchmark[histogram]
生成历史比较图
# 在测试运行后生成 pytest test_benchmark.py --benchmark-histogram
这将生成 HTML 文件,包含直方图比较不同测试函数的性能。
更详细的图表生成
# 使用 pytest-benchmark 的 save_data 功能 pytest test_benchmark.py --benchmark-save=my_benchmark pytest test_benchmark.py --benchmark-compare --benchmark-autosave
生成性能回归图表
# 比较多次运行的性能变化 pytest test_benchmark.py --benchmark-compare=0001 --benchmark-compare-fail=min:5%
自定义可视化示例
# test_benchmark.py
import pytest
import time
def test_my_function(benchmark):
@benchmark
def result():
time.sleep(0.001) # 模拟耗时操作
return sum(range(1000))
# 可以访问测量数据
stats = benchmark.stats
print(f"Mean time: {stats.mean}")
生成性能趋势图
安装额外依赖:
pip install pygal
使用包含历史对比的测试:
# 多次运行后生成趋势 pytest test_benchmark.py --benchmark-save=run1 pytest test_benchmark.py --benchmark-save=run2 pytest test_benchmark.py --benchmark-compare --benchmark-columns=min,max,mean
高级可视化(自定义脚本)
# visualize_benchmarks.py
import json
import matplotlib.pyplot as plt
import numpy as np
with open('.benchmarks/your_benchmark_file.json', 'r') as f:
data = json.load(f)
# 提取数据
test_names = [b['name'] for b in data['benchmarks']]
times = [b['stats']['mean'] / 1e6 for b in data['benchmarks']] # 转换为毫秒
# 绘制条形图
plt.figure(figsize=(10, 6))
plt.bar(test_names, times)
plt.ylabel('Mean Time (ms)')'Benchmark Results')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('benchmark_results.png')
集成 CI/CD 可视化
# .github/workflows/benchmarks.yml
name: Benchmarks
on: [push]
jobs:
benchmark:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run benchmarks
run: |
pip install pytest-benchmark
pytest test_benchmark.py --benchmark-json output.json
- name: Store results
uses: actions/upload-artifact@v2
with:
name: benchmark-results
path: output.json
推荐工具组合
- pytest-benchmark + pytest-html:生成带图表的详细报告
- pytest-benchmark + pandas:数据分析和自定义图表
- pytest-benchmark + Jupyter:交互式分析和可视化
通过这些方法,你可以快速获得性能测试结果的可视化呈现,帮助分析代码性能变化趋势。