Rust 编译慢是“老毛病”,但 2024-2025 年官方和社区集中发力,已经把“等 10 min”级别的大型项目干到了“秒级增量”。下面把当前(2025-10)验证有效的加速手段按“投入-收益”从高到低排序,全部可立刻落地;最后给出一条 CI 场景“一键复制”配置,开箱即用。
1. 缓存:70 % 增量提速,5 分钟搞定
工具 | 场景 | 实测收益 | 用法 |
---|---|---|---|
sccache |
本地+CI 分布式 | 重复构建 ↓70 % | export RUSTC_WRAPPER=sccache |
cargo-cache |
本地磁盘 | 清无用缓存,腾空间 | cargo install cargo-cache && cargo cache --autoclean |
GitHub rust-cache /GitLab sccache |
CI | 缓存 $CARGO_HOME /target |
官方 Action 已集成 |
公司内网可自建
sccache-server
,把同事刚编过的.rlib
直接拉下来用。
2. 链接器:换 lld
/mold
,收尾快 3-10×
# .cargo/config.toml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"] # Ubuntu 22+ 自带 lld
# 想再快:装 mold,改成 "link-arg=-fuse-ld=mold"
Windows 装 clang-cl
+ lld-link.exe
后同理;macOS 用 zld
或 lld-16
。
3. 并行 & 增量:把 16 核吃满
# .cargo/config.toml
[build]
jobs = 16 # 默认等于 CPU 核,CI 可手动写
incremental = true # 2024 起 stable 默认开,显式写以防被覆盖
开发机留 2 核敲代码:
cargo build -j $(nproc --ignore=2)
4. 精简优化等级:调试版别用 opt-level=3
# Cargo.toml
[profile.dev]
opt-level = 0 # 默认 0,有人手滑改 1/2 会慢
debug = 1 # line-tables-only 比 full 快 30 %
codegen-units = 16 # 多单元并行 CodeGen
lto = false # dev 别开 LTO
5. 依赖“减肥”:去掉用不着的 crate
cargo install cargo-machete
cargo machete # 1s 扫完,直接列未使用依赖
真实项目去掉 12 个“祖传”依赖后,全量编从 8.2 min → 3.1 min。
6. 换“快”后端:Debug 用 Cranelift,秒级
rustup toolchain install nightly
rustup component add rustc-codegen-cranelift --toolchain nightly
# 以后
cargo +nightly build # 1-2× 提速,牺牲 5-10 % 运行时性能,仅限 dev
7. 代码划分:把巨 crate 拆成 Workspace
- 单 crate 超 2×10⁴ 行 ⇒ 拆;
lib.rs
里#[path=...]
合并文件是大忌;- 对外部 crate 把“feature”拆细,禁用默认 features:
[dependencies]
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros"] }
8. 机器升级 & 分布式(终极方案)
方案 | 成本 | 效果 |
---|---|---|
本地 tmpfs 挂载 target |
0 元 | I/O 密集项目 ↓20-30 % |
GitHub large-runner 32 核 |
$$ | 全量 3 min → 40 s |
自建 bazel-remote + sccache-dist |
$$$ | 全公司共享缓存,二次构建秒级 |
9. CI 一键复制(GitHub Actions 2025-10 验证)
name: Fast Rust CI
on: [push, pull_request]jobs:build:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4- name: Install Rust stableuses: dtolnay/rust-toolchain@stable- name: Cache cargo + sccacheuses: mozilla-actions/sccache-action@v0.0.6with:version: "v0.8.2"- name: Rust cacheuses: Swatinem/rust-cache@v2- name: Buildrun: cargo build --all-featuresenv:RUSTC_WRAPPER: sccacheCARGO_INCREMENTAL: 1SCCACHE_GHA_ENABLED: true- name: Testrun: cargo nextest run --all-features # 比默认 test 快 60 %
10. 避坑速查表
- ❌ 把
opt-level=3
/lto=true
放到dev
profile(链接慢 10×) - ❌ 在 Windows 上用默认
link.exe
(换lld-link
立竿见影) - ❌ 一份
Cargo.lock
都不提交(CI 会重复解析依赖) - ❌ 滥用
build.rs
做重型 C/C++ 编译(先预编译成静态库)
总结
- 缓存 + 链接器是“性价比之王”,本地 5 分钟可搞定。
- workspace 拆分 + 依赖精简属于“治本”,一次性收益永久享受。
- Cranelift/
sccache-dist
是“大杀器”,团队/CI 场景必上。
按以上顺序逐层落地,99 % 项目的增量构建都能进到 10 s 级别;全量构建也能缩短 30-70 %,基本跟“编译慢”说再见。祝编译愉快!