在 Debian 上优化 Rust 编译(速度和产物性能)可以从编译速度、构建配置、系统环境、依赖管理几个方面入手。下面按实用程度分类说明。
sccache(强烈推荐)避免重复编译依赖:
cargo install sccache
export RUSTC_WRAPPER=sccache
可写入 ~/.cargo/config.toml:
[build]
rustc-wrapper = "sccache"
mold 或 lld 链接器(Debian 支持好)安装:
sudo apt install mold
配置 ~/.cargo/config.toml:
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
或(lld):
sudo apt install lld
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
[profile.dev]
debug = 0
默认开启,但确保:
[build]
incremental = true
cargo build -j N限制或提高并行数,适配 Debian 服务器 CPU:
cargo build -j $(nproc)
cargo build --release
Cargo.toml:
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
strip = true
⚠️ lto = true 会显著延长编译时间,但运行更快。
Debian 自带 Rust 通常较旧:
curl https://sh.rustup.rs -sSf | sh
sudo apt install build-essential clang cmake pkg-config libssl-dev
对 I/O 密集服务有帮助。
tokio vs async-std)cargo tree 分析[workspace]
members = ["core", "api", "cli"]
避免单 crate 过大。
cargo diet(减小依赖)# ~/.cargo/config.toml
[build]
rustc-wrapper = "sccache"
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
export SCCACHE_DIR=/cache/sccache
cargo build --release
如果你愿意,可以告诉我:
我可以给你一套针对性配置。