最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论