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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744673825a4587208.html
评论列表(0条)