基准测试是评估代码性能的基础手段,用于量化函数的执行时间或操作吞吐量。Rust生态提供了两种主要工具:
#[bench]框架:通过#[bench]属性标记基准测试函数,使用cargo bench命令运行。例如:#[cfg(test)]
mod benches {
use super::*;
use test::Bencher;
#[bench]
fn bench_add_two(b: &mut Bencher) {
b.iter(|| add_two(2)); // 测试add_two函数的性能
}
}
运行后会输出每个基准测试的执行时间(如纳秒/次)。[dev-dependencies] criterion = "0.4";benches目录及测试文件(如my_benchmark.rs);cargo bench生成详细报告(target/criterion/report/index.html)。性能分析用于定位代码中的性能瓶颈(如CPU热点、内存占用过高),常用工具包括:
perf工具:Linux内核提供的性能分析工具,可记录函数调用栈和执行时间。步骤:
perf:yum install perf;perf record -g ./target/release/your_program;perf report -n --stdio(文本模式)或生成火焰图(见下文)。callgrind可分析函数调用耗时:
valgrind --tool=callgrind ./target/release/your_program;kcachegrind callgrind.out.*(可视化调用关系)。perf记录的调用栈数据转换为火焰图,直观展示热点函数。步骤:
FlameGraph工具:git clone https://github.com/brendangregg/FlameGraph.git;perf record -g ./target/release/your_program && perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > perf.svg。压力测试用于模拟高并发场景,验证系统在极限负载下的稳定性(如请求延迟、错误率)。常用工具:
oha:Rust编写的开源HTTP性能测试工具,支持HTTP/1/2、实时TUI显示(请求数、响应时间、成功率)。安装:cargo install oha;使用示例:oha -n 1000 -c 50 https://example.com # 发送1000个请求,并发50
wrk/ab:传统压力测试工具,适合快速测试。例如wrk:wrk -t4 -c100 -d30s https://example.com # 4线程、100并发、30秒测试
基准测试结果受编译优化影响较大,需在Cargo.toml中配置release模式及优化参数:
[profile.release]
opt-level = 3 # 最高优化级别
lto = true # 链接时优化
codegen-units = 1 # 减少代码生成单元,提升优化效果
panic = 'abort' # 避免运行时panic开销
运行基准测试前需编译release版本:cargo build --release。
将性能测试集成到CI/CD流程(如GitHub Actions),确保每次代码提交不会降低性能。示例配置(.github/workflows/bench.yml):
name: Rust Benchmark
on: [push, pull_request]
jobs:
bench:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with: { toolchain: stable, override: true }
- run: cargo install cargo-benchcmp
- run: cargo bench --no-run # 编译基准测试
- name: Run benchmarks
run: cargo bench
- name: Compare results
if: github.event_name == 'pull_request'
run: cargo benchcmp old new --threshold 5% # 对比前后性能变化
通过cargo benchcmp工具对比不同提交的基准测试结果,设置阈值(如5%)预警性能退化。