Rust 在 Debian 上的性能调优指南
一 工具链与构建环境
rustup update。在 Debian 上可通过官方脚本安装:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh。cargo fmt、cargo clippy、cargo bench,用于格式化、静态检查与基准测试,保障可维护性与性能回归可控。二 编译配置与优化级别
cargo build --release;在 Cargo.toml 的 [profile.release] 中设置优化级别与链接时优化(LTO)。[profile.release]
opt-level = 3 # 最高级别优化
lto = "thin" # 折中方案:跨 crate 优化且构建更快
codegen-units = 1 # 更大优化范围,编译更慢
panic = "abort" # 减小体积并略降开销(无需 panic 恢复时)
RUSTFLAGS 中传入 -C target-cpu=native(仅在目标机器运行)。opt-level = "z"(更小)或 opt-level = "s"(体积与速度折中)。三 代码与运行时优化
Vec/String 等容器 预分配容量,利用引用与借用避免不必要复制。std::thread 并行化;I/O 密集任务用 tokio 等异步运行时;减少锁争用,必要时用 parking_lot 等更高效同步原语。#[inline] 提示编译器。unsafe:仅在确保安全且确有收益时绕过边界检查等安全检查。四 性能分析与基准测试
cargo bench 或 criterion.rs 建立稳定、可统计的性能回归套件。sudo perf record -g target/release/your_appsudo perf reportcargo install flamegraphRUSTFLAGS="-C target-cpu=native" cargo flamegraph --bin your_program五 系统与部署调优
ulimit -n 65535 或在 /etc/security/limits.conf 配置);优先 SSD;必要时用 taskset 绑定 CPU 亲和性 减少上下文切换。/etc/sysctl.conf,如 vm.swappiness、net.core.somaxconn 等网络/内存相关参数。target-cpu=native;对分发体积敏感时可用 opt-level="z" 或 panic="abort" 搭配 LTO 减小体积。