Rust编译选项及配置

不关注实现,记录如何更好使用rust编译器,或者记录一些和编译相关有用的工具。

0. 设置项

0.1 Cargo.toml

lto

rust release编译虽然已经设置opt-level为最高等级3,但lto默认设置为false,可以尝试设置为true提升性能。

开了lto之后,即使函数没有手动标注inline,也可能跨crate内联。

[profile.release]
lto = true

codegen-units

在release中,codegen-units默认为16,我们可以将其改成1,可能让编译器发现更多可以优化性能的地方。

[profile.release]
codegen-units = 1

debug

release模式默认是没有debug信息,可以手动设置。但是rust标准库中还是没有debug信息。

[profile.release]
debug = true

0.2 config.toml

[env]设置环境变量

[env],比如下面可以每次打印详细的堆栈信息

[env]
RUST_BACKTRACE = {value = "full"}

[build]设置编译选项

 [build]
 rustflags = ["-C", "target-cpu=native"] # 可以让编译器选择机器支持的指令,比如avx

通过rustc --print cfgrustc --print cfg -C target-cpu=native 可以比较不同的feature。

更多关于codegen选项,比如关闭自动SIMD,可看这里

1. 静态分析

cargo expand

宏展开,详见 cargo-expand

cargo remark

cargo install cargo-remark

cargo remark build

可以查看 LLVM 生成的optimization remarks,即 LLVM 告诉你代码中 优化X 没有做是因为有 原因Y 的限制,程序员可以尝试用消除 原因Y 的限制来提升程序性能。但这不是那么容易的,详见 Inspecting rustc LLVM optimization remarks using cargo-remark

查看MIR

rustc [filename].rs -Z mir-opt-level=0 --emit mir --edition 2021

需要使用nightly,也可以直接在rust_playground 上看

cargo check

只检查语法,不真的生成产物,用时少,可以提高开发效率

rustfilt

demangle Rust symbol names

用法举例

 objdump -Mintel -S -d ./rust-playground | rustfilt

2. 动态profile

PGO-optimized

编译运行程序,收集运行过程中程序的各项指标,利用这些信息再次编译程序,详见 Profile-guided Optimization