温馨提示×

centos rust编译怎优化

小樊
56
2026-10-20 08:53:33
栏目: 编程语言

在 CentOS 上优化 Rust 编译(速度 / 体积 / 性能)通常从 编译配置、工具链、系统环境 三方面入手。下面按「实用程度」给你一套方案。


一、编译速度优化(最常用)

1️⃣ 使用 release 但加快编译

# Cargo.toml
[profile.release]
opt-level = 2
lto = false
codegen-units = 256

如果你不关心最终性能,只关心编译快:

[profile.dev]
opt-level = 0
debug = false

2️⃣ 使用 sccache(强烈推荐)

避免重复编译依赖:

cargo install sccache
export RUSTC_WRAPPER=sccache

CentOS 安装依赖:

yum install -y openssl-devel

3️⃣ 使用 mold 链接器(速度提升明显)

yum install -y mold
# .cargo/config.toml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]

4️⃣ 并行编译 & 限制 jobs

cargo build -j 8

或修改:

export CARGO_BUILD_JOBS=8

二、生成体积优化(服务器/容器常用)

1️⃣ 标准体积优化

[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true

2️⃣ 使用 upx(可选)

yum install -y upx
upx --best target/release/your_bin

三、运行性能优化

1️⃣ 最大性能配置

[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
target-cpu = "native"
RUSTFLAGS="-C target-cpu=native"

⚠️ 注意:native 编译的二进制不能跨机器


四、CentOS 特有注意点

1️⃣ glibc 版本问题

CentOS 7 的 glibc 较老,建议:

  • 用 CentOS 8 / Rocky / Alma
  • 或静态编译:
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "target-feature=+crt-static"]

2️⃣ 使用新版本 GCC / Clang

yum install -y gcc-toolset-12
scl enable gcc-toolset-12 bash

3️⃣ 使用 musl(容器友好)

rustup target add x86_64-unknown-linux-musl
cargo build --target x86_64-unknown-linux-musl

五、推荐组合(实战)

✅ 开发快

sccache + mold + dev profile

✅ 生产小

opt-level=z + lto + strip

✅ 高性能

opt-level=3 + fat lto + native cpu

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

  • CentOS 版本(7 / 8 / Stream)
  • 用途(服务器 / CLI / 容器 / 嵌入式)
  • 是否交叉编译

我可以直接给你 一套可复制的 Cargo.toml + 命令。

0 踩