指南:剖析运行时基准测试

English version: profiling.md

剖析运行时基准测试以定位耗时。支持两种剖析器:Cachegrind(指令级,基于 Valgrind)与 perf-record(采样,Linux perf)。Cachegrind 还支持比较两个 rustc 构建。

前置条件

  • local-benchmarking 前置条件的全部内容。
  • cachegrindPATH 上有 valgrindcg_annotatecg_diff。构建较新 Valgrind;precise-cachegrind 特性构建时还需 DEP_VALGRIND=<path-to-valgrind>/include
  • perf-recordPATH 上有 perf

验证:

valgrind --version && cg_annotate --version && perf --version

步骤 1——(可选)启用 precise cachegrind

precise cachegrind 用 Valgrind 客户端请求在 bench(env) 前后精确启停插桩,把构造/预热排除在剖析之外。用该特性构建 collector 与基准测试 crate:

DEP_VALGRIND=/usr/include cargo build --release --features precise-cachegrind

步骤 2——剖析单个 rustc

# Cachegrind(指令级)
./target/release/collector profile_runtime <RUSTC> cachegrind --group std

# perf-record(采样)
./target/release/collector profile_runtime <RUSTC> perf-record --group std

# 多迭代以便剖析器采集更多数据
./target/release/collector profile_runtime <RUSTC> cachegrind --group std --iterations 20

<RUSTC> 为路径或 +toolchain(同 bench_runtime_local)。--iterations(默认 5)控制被剖析函数运行次数,以便剖析器有足够样本。

剖析始终用缓存(原地)编译并强制开启调试信息,以便生成剖析中有文件名与行号。

步骤 3——查找输出

剖析写入 results-runtime/

  • Cachegrindcgout-<rustc_id>-<group>-<bench>.<N>(原始)与 cgann-<rustc_id>-<group>-<bench>.<N>(注解)。
  • perf-recordperf-<rustc_id>-<group>-<bench>.<N>(原始)与 perfreport-<rustc_id>-<group>-<bench>.<N>(注解)。

collector 末尾打印路径:

Profiling complete, result can be found in `results-runtime/...`

步骤 4——比较两个 rustc 构建(仅 cachegrind)

比较修改版 rustc 与基线,精确查看指令变化:

./target/release/collector profile_runtime <rustc-modified> cachegrind --rustc2 <rustc-baseline> --group std

collector 剖析两个工具链,再对每个基准测试的 cachegrind 输出对运行 cg_diff 并注解差异。差异与各工具链剖析并列存储,collector 打印:

Diff stored in `results-runtime/...`

--rustc2perf-record 不支持。 比较请用 cachegrind。

步骤 5——剖析组内单个基准测试

profile_runtime 剖析组内每个基准测试。要缩小范围,用与 bench_runtime_local 相同的过滤标志:

./target/release/collector profile_runtime <RUSTC> cachegrind --group std \
    --include std_bench::hash --iterations 10

(此处同样接受 --include/--exclude/--exclude_suffix/--exact_match。)

故障排除

  • valgrind 未安装——安装 valgrind(及 cg_annotate/cg_diff,通常同包)。
  • 空剖析——基准测试可能太快;提高 --iterations
  • --rustc2 perf-record 报错——perf-record 无比较支持;改用 cachegrind。
  • 注解无行号——剖析强制开启调试信息;若自定义基准测试 crate 未带调试信息,请重建。

下一步