温馨提示×

centos rust编译如何提速

小樊
53
2026-10-23 09:01:12
栏目: 编程语言

在 CentOS 上编译 Rust 项目慢,通常可以从工具链、编译参数、依赖管理、系统资源几个方面来提速。下面按「见效快 → 进阶优化」给你一套实用方案。


一、立竿见影的提速手段

1. 使用 cargo build --release 的替代:调试也别太慢

  • 开发阶段用:
cargo build

但如果只是想跑测试:

cargo test --no-run

2. 开启并行编译(默认已开,但可确认)

export CARGO_BUILD_JOBS=$(nproc)

3. 使用 sccache(强烈推荐)

效果非常明显,尤其多次编译或 CI 环境。

cargo install sccache
export RUSTC_WRAPPER=sccache

持久化(写入 ~/.bashrc):

echo 'export RUSTC_WRAPPER=sccache' >> ~/.bashrc

二、减少重复编译

4. 使用 cargo-chef(适合 CI / 服务器)

先只编译依赖:

cargo install cargo-chef
cargo chef prepare
cargo chef cook

5. 拆分 crate(架构层面)

  • 大项目拆成多个 crate
  • 避免修改核心库导致全量重编

三、编译参数优化(开发 / 发布不同)

6. 开发阶段关闭优化

Cargo.toml:

[profile.dev]
opt-level = 0
debug = true
incremental = true

7. 使用增量编译(默认开启)

export CARGO_INCREMENTAL=1

四、CentOS 系统级优化

8. 使用新版本 Rust(非常关键)

CentOS 自带 Rust 往往很旧:

rustup update stable

推荐用 rustup 而不是 yum:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

9. 使用更快的 linker

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"]

或使用 lld

yum install -y lld
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

五、CPU / 内存层面

10. 保证足够内存

  • Rust 编译吃内存
  • 建议 ≥ 4GB(8GB 更舒服)

查看:

free -h

11. 使用 tmpfs(小项目有效)

export CARGO_TARGET_DIR=/dev/shm/target

六、可选:换编译器前端(进阶)

12. 使用 Cranelift(开发阶段)

rustup component add rustc-codegen-cranelift-preview
CARGO_PROFILE_DEV_CODEGEN_BACKEND="cranelift"

推荐组合(CentOS 实测有效)

✅ rustup + sccache + mold + incremental
✅ 多 crate 拆分
✅ CI 用 cargo-chef


如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • 项目规模(小型 CLI / Web 服务 / 大型系统)
  • 是否在 Docker / CI 中编译

我可以直接给你一套最优配置模板。

0 踩