Ubuntu 上优化 Rust 性能的可落地清单
一 构建与链接优化
[profile.release]
opt-level = "s" # 或 "z"
lto = true
codegen-units = 1
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
# 若已安装 mold:
# rustflags = ["-C", "link-arg=-fuse-ld=mold"]
[build]
jobs = 16
incremental = true
rustup toolchain install nightly
rustup component add rustc-codegen-cranelift --toolchain nightly
cargo +nightly build
export RUSTC_WRAPPER=sccache
# CI 可配合缓存 $CARGO_HOME 与 target
定期清理无用缓存并维护依赖,减少“膨胀”。二 代码与运行时优化
三 性能分析与定位瓶颈
sudo perf record -g target/release/your_program
sudo perf report
cargo install flamegraph
flamegraph --bin your_program
四 系统与硬件层面的优化
五 一键可用的最小配置示例
[build]
jobs = 16
incremental = true
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
# 若已安装 mold:
# rustflags = ["-C", "link-arg=-fuse-ld=mold"]
[profile.release]
opt-level = "s" # 或 "z";追求极致性能可用 "3"
lto = true
codegen-units = 1
export RUSTC_WRAPPER=sccache
# 定期清理
cargo install cargo-cache && cargo cache --autoclean
rustup toolchain install nightly
rustup component add rustc-codegen-cranelift --toolchain nightly
cargo +nightly build
cargo install flamegraph
flamegraph --bin your_program
sudo perf record -g target/release/your_program && sudo perf report
以上配置覆盖“构建-链接-运行-分析”的关键环节,按项目体量与场景微调即可获得稳定收益。