在Debian系統上進行Rust代碼性能測試,可按以下步驟操作,主要工具為Criterion.rs(推薦)和perf:
在Cargo.toml中添加依賴:
[dev-dependencies]
criterion = "0.5" # 使用最新版本
在benches/目錄下創建測試文件(如my_benchmark.rs):
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 | 1 => n,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
fn bench_fibonacci(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, bench_fibonacci);
criterion_main!(benches);
black_box防止編譯器優化被測代碼。執行命令:
cargo bench
結果會輸出至終端,并生成HTML報告(target/criterion/report/index.html),包含時間、統計分析和圖表。
sudo apt-get install linux-tools-common linux-tools-$(uname -r)
運行程序并記錄性能數據:
perf record -g ./target/release/your_program
生成報告:
perf report -n --stdio
或生成火焰圖(需安裝flamegraph工具):
perf script | ./stackcollapse-perf.pl | ./flamegraph.pl > perf.svg
perf使用。black_box避免編譯器優化掉測試代碼。通過上述工具,可精準定位Rust代碼的性能瓶頸,輔助優化。