如何通过Linux优化Rust的编译速度
小樊
39
2025-11-30 13:15:54
Linux下优化 Rust 编译速度的可落地方案
一 缓存与构建管线
- 启用 sccache 做编译结果缓存(本地与 CI 通用),重复构建通常可下降约70%:
- 本地:export RUSTC_WRAPPER=sccache
- CI:使用 GitHub 的 rust-cache Action 或自建 sccache-server,缓存 $CARGO_HOME 与 target/
- 定期清理无用缓存,避免磁盘膨胀与命中率下降:cargo install cargo-cache && cargo cache –autoclean
- 保持增量编译开启(stable 已默认开启):cargo build 默认使用增量;必要时在配置中显式声明,避免被覆盖
二 并行度与链接器
- 并行构建:将构建并发数设置为接近 CPU 核数;开发机建议保留2 核给编辑器/终端:cargo build -j $(nproc --ignore=2);在 .cargo/config.toml 中可固定:[build] jobs = 16
- 更快的链接器(大幅缩短链接尾段):
- LLD:稳定、通用;配置示例(x86_64 GNU):
- [target.x86_64-unknown-linux-gnu]
linker = “clang”
rustflags = [“-C”, “link-arg=-fuse-ld=lld”]
- Mold:追求极致链接速度;将上一行的 lld 换为 mold 即可
- 链接器选择对整体构建时长影响显著,优先尝试 Mold,其次 LLD
三 Cargo Profile 与代码生成策略
- 开发阶段(dev):优先速度,避免重量级优化
- [profile.dev]
opt-level = 0
debug = 1 # 仅行表,较 full 更快
codegen-units = 16 # 并行 CodeGen
lto = false
incremental = true
- 发布阶段(release):在速度与性能间平衡
- [profile.release]
opt-level = 2 # 多数场景的性价比最佳
lto = “thin” # 兼顾优化与编译时长
codegen-units = 16 # 保持并行度
- 体积敏感或嵌入式:
- [profile.min-size]
inherits = “release”
opt-level = “z”
lto = true
codegen-units = 1
panic = “abort”
strip = “symbols”
- 调试与性能分析并存(便于 flamegraph/perf):
- [profile.bench]
inherits = “release”
debug = true
- 按依赖精细控制(示例:对关键依赖更激进优化)
- [profile.release.package.“my_critical_lib”]
opt-level = 3
codegen-units = 1
- 原则:dev 追求编译快、release 追求运行快,必要时用自定义 profile 区分场景
四 依赖与工程结构优化
- 精简依赖树:cargo install cargo-machete && cargo machete,移除未使用依赖,常能显著缩短全量构建时间
- 禁用默认特性与按需启用:例如 tokio = { version = “1”, default-features = false, features = [“rt-multi-thread”, “macros”] }
- 拆分巨型 crate:当单 crate 超过约2×10⁴ 行时,拆分为 workspace 更易并行与缓存命中
- 避免在 lib.rs 中用 #[path=…] 拼接模块,保持清晰的模块边界与依赖关系
五 系统与 I/O 优化
- 使用 Tmpfs 加速临时构建(适合 CI 或本地实验):
- mkdir -p /mnt/fast
- mount -t tmpfs -o size=666M tmpfs /mnt/fast
- 在 /mnt/fast 下克隆与构建(注意数据易失)
- 适度调大虚拟内存相关阈值(大规模链接/大量内存映射时):sysctl -w vm.max_map_count=262144
- 使用 SSD/NVMe 与充足的 CPU/内存,并监控系统资源(如 top/htop),避免 I/O 或内存成为瓶颈
六 快速配置示例与 CI 模板
- 本地开发用的 .cargo/config.toml(按需调整 jobs)
- [build]
jobs = 16
incremental = true
- [target.x86_64-unknown-linux-gnu]
linker = “clang”
rustflags = [“-C”, “link-arg=-fuse-ld=lld”]
- [profile.dev]
opt-level = 0
debug = 1
codegen-units = 16
lto = false
incremental = true
- [profile.release]
opt-level = 2
lto = “thin”
codegen-units = 16
- GitHub Actions 片段(缓存 + sccache)
- uses: actions/cache@v4
with:
path: |
~/.cargo
target
key: ${{ runner.os }}-rust-${{ hashFiles(‘**/Cargo.lock’) }}
- env:
RUSTC_WRAPPER: sccache
- 可选:在开发机上使用更快后端(仅 dev,需 nightly)
- rustup toolchain install nightly
- rustup component add rustc-codegen-cranelift --toolchain nightly
- cargo +nightly build(调试构建通常可提速,运行性能略降约5–10%)