Hyperfine 基准测试¶
为什么要学 Hyperfine¶
Hyperfine 是一个命令行基准测试工具,用 Rust 编写。它能够准确测量命令的执行时间,支持预热运行、统计分析、多命令对比和结果导出。当你需要比较不同程序、算法或配置的性能时,Hyperfine 提供了科学的测量方法,避免了手动 time 命令带来的不准确性。
核心概念¶
| 概念 | 白话解释 | 用途 |
|---|---|---|
| Warmup | 预热运行 | 消除缓存冷启动影响 |
| Runs | 运行次数 | 多次运行取统计值 |
| Mean/Median | 均值/中位数 | 统计中心趋势 |
| Stddev | 标准差 | 衡量结果稳定性 |
| Min/Max | 最小/最大值 | 极端值范围 |
| Relative Speed | 相对速度 | 与最快命令的倍数关系 |
安装配置¶
快速上手¶
# 基本测量
hyperfine 'sleep 0.3'
# 多次运行(默认至少10次)
hyperfine --runs 20 'ls -la'
# 带预热
hyperfine --warmup 3 'python script.py'
# 对比两个命令
hyperfine 'fd -e py' 'find . -name "*.py"'
# 输出示例:
# Benchmark 1: fd -e py
# Time (mean ± σ): 4.2 ms ± 0.3 ms
# Range (min … max): 3.8 ms … 5.1 ms
#
# Benchmark 2: find . -name "*.py"
# Time (mean ± σ): 45.6 ms ± 2.1 ms
# Range (min … max): 42.3 ms … 51.2 ms
#
# Summary
# fd -e py ran 10.86 ± 0.89 times faster than find . -name "*.py"
进阶用法¶
带参数对比¶
# 对比不同排序算法
hyperfine \
'python sort_bubble.py' \
'python sort_quick.py' \
'python sort_merge.py' \
--warmup 3
# 参数化测试
hyperfine --parameter-scan threads 1 8 \
'make -j {threads}'
# 列表参数
hyperfine --parameter-list lang python3,node,ruby \
'{lang} benchmark.{lang}'
准备和清理命令¶
# 每次运行前清理缓存
hyperfine \
--prepare 'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches' \
'grep -r pattern /path'
# 每次运行前执行准备
hyperfine \
--prepare 'make clean' \
'make build'
# 清理命令
hyperfine \
--cleanup 'rm -f output.bin' \
'gcc -O2 -o output.bin main.c'
导出结果¶
# JSON 格式
hyperfine 'command1' 'command2' --export-json results.json
# Markdown 格式
hyperfine 'command1' 'command2' --export-markdown results.md
# CSV 格式
hyperfine 'command1' 'command2' --export-csv results.csv
# 生成图表(需要额外脚本)
# 使用 hyperfine 附带的 Python 脚本
python3 scripts/plot_whisker.py results.json -o benchmark.png
统计配置¶
# 最少运行次数
hyperfine --min-runs 50 'command'
# 最少运行时间
hyperfine --min-benchmarking-time 10 'command' # 至少运行10秒
# 忽略失败
hyperfine --ignore-failure 'command_that_may_fail'
# Shell 选择
hyperfine --shell=none './binary' # 不通过 shell(更准确)
常见问题¶
Q: 结果波动大怎么办?¶
- 增加运行次数
--runs 50 - 增加预热
--warmup 5 - 关闭其他程序减少干扰
- 使用
--shell=none避免 shell 开销
Q: 如何测量内存使用?¶
Hyperfine 只测量时间。内存测量可以配合 /usr/bin/time -v 或 valgrind --tool=massif。
Q: 与 time 命令的区别?¶
time:单次测量,不够准确hyperfine:多次运行、统计分析、自动对比
参考资源¶
- GitHub:https://github.com/sharkdp/hyperfine
- 使用示例:https://github.com/sharkdp/hyperfine#examples
- 可视化脚本:https://github.com/sharkdp/hyperfine/tree/master/scripts