在 CentOS 上编译 Rust 项目慢,通常可以从工具链、编译参数、依赖管理、系统资源几个方面来提速。下面按「见效快 → 进阶优化」给你一套实用方案。
cargo build --release 的替代:调试也别太慢cargo build
但如果只是想跑测试:
cargo test --no-run
export CARGO_BUILD_JOBS=$(nproc)
sccache(强烈推荐)效果非常明显,尤其多次编译或 CI 环境。
cargo install sccache
export RUSTC_WRAPPER=sccache
持久化(写入 ~/.bashrc):
echo 'export RUSTC_WRAPPER=sccache' >> ~/.bashrc
cargo-chef(适合 CI / 服务器)先只编译依赖:
cargo install cargo-chef
cargo chef prepare
cargo chef cook
crateCargo.toml:
[profile.dev]
opt-level = 0
debug = true
incremental = true
export CARGO_INCREMENTAL=1
CentOS 自带 Rust 往往很旧:
rustup update stable
推荐用 rustup 而不是 yum:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
CentOS 默认 ld 较慢,可换 lld 或 mold
mold(推荐,极快)yum install -y mold
~/.cargo/config.toml:
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
lldyum install -y lld
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
查看:
free -h
export CARGO_TARGET_DIR=/dev/shm/target
Cranelift(开发阶段)rustup component add rustc-codegen-cranelift-preview
CARGO_PROFILE_DEV_CODEGEN_BACKEND="cranelift"
✅ rustup + sccache + mold + incremental
✅ 多 crate 拆分
✅ CI 用 cargo-chef
如果你愿意,可以告诉我:
我可以直接给你一套最优配置模板。