admin管理员组文章数量:1390503
I have some computation tests where I want the code to automatically run a more shallow test if the code is compiled non-optimized, and run a deeper test if optimization is enabled. It appears there are no environment variables that indicate this at compile time.
How can the code itself determine what optimization it has been compiled in? Possible?
I have some computation tests where I want the code to automatically run a more shallow test if the code is compiled non-optimized, and run a deeper test if optimization is enabled. It appears there are no environment variables that indicate this at compile time.
How can the code itself determine what optimization it has been compiled in? Possible?
Share Improve this question asked Mar 14 at 4:15 twig-frothtwig-froth 672 silver badges6 bronze badges1 Answer
Reset to default 3There is no way to do this without some kind of support from the build tooling. Optimizations generally try to follow the as-if rule, which means that if you could tell what optimization level was used from within the program, the optimizer has broken this rule in some way.
However, you can use a build script to accomplish this, by proxying the value of the environment variable OPT_LEVEL
from within the build script to rustc
using cargo::rustc-env
, which you would then be able to read from your program using env!
.
For example, you could use this build script:
fn main() {
println!(
"cargo::rustc-env=OPT_LEVEL={}",
std::env::var("OPT_LEVEL").unwrap()
);
}
Then, given this sample program:
fn main() {
println!("Compiled with optimization level {}", env!("OPT_LEVEL"));
}
We can observe the optimization level change depending on whether the program is run in release mode.
$ cargo run 2>/dev/null
Compiled with optimization level 0
$ cargo run -r 2>/dev/null
Compiled with optimization level 3
本文标签: How can Rust code determine the optimization level it is compiled inStack Overflow
版权声明:本文标题:How can Rust code determine the optimization level it is compiled in? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744673824a2618990.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论