How can Rust code determine the optimization level it is compiled in? - Stack Overflow

I have some computation tests where I want the code to automatically run a more shallow test if the cod

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744673825a4587208.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信