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 badges
Add a comment  | 

1 Answer 1

Reset to default 3

There 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