使用稳定版/测试版时忽略基准 [英] Ignore benchmarks when using stable/beta

查看:111
本文介绍了使用稳定版/测试版时忽略基准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些基准测试的文件,并希望针对稳定版,测试版和每晚进行测试.但是,要么我不使用基准测试,要么不使用稳定版/测试版抱怨.使用稳定版/测试版时,是否可以隐藏所有基准测试部分?

I have a file with some benchmarks and tests and would like to test against stable, beta and nightly. However, either I don't use the benchmark or stable/beta complain. Is there a way to hide all the benchmark parts when using stable/beta?

作为示例,来自的以下代码:

As an example the following code from the book:

#![feature(test)]

extern crate test;

pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;

    #[test]
    fn it_works() {
        assert_eq!(4, add_two(2));
    }

    #[bench]
    fn bench_add_two(b: &mut Bencher) {
        b.iter(|| add_two(2));
    }
}

我正在使用rustup,并且希望同一个文件可用于所有构建,并调用类似的内容:

I'm using rustup and would like the same file to work with all the builds, calling something like:

rustup run nightly cargo bench --bin bench --features "bench"
rustup run nightly cargo test --bin bench --features "bench"
rustup run beta cargo test --bin bench
rustup run stable cargo test --bin bench

我能够用#![cfg_attr(feature = "bench", feature(test))]隐藏#![feature(test)].我可以做与基准测试其余部分类似的事情吗?什么是功能标记的好资源?

I was able to hide the #![feature(test)] with #![cfg_attr(feature = "bench", feature(test))]. Can I do something similar to the rest of the benchmark parts? What is a good resource for feature flags?

推荐答案

在我的项目中,我将基准放置在单独的模块中,就像进行测试一样.然后,我创建一个启用它们的货运功能.在此摘录中,我使用了功能名称unstable,但您可以使用任何想要的功能:

In my projects, I place benchmarks in a separate module, just like I do for tests. I then create a Cargo feature that enables them. In this excerpt, I used the feature name unstable, but you can use anything you'd like:

Cargo.toml

# ...

[features]
unstable = []

# ...

src/lib.rs

#![cfg_attr(feature = "unstable", feature(test))]

#[cfg(test)]
mod tests {
    #[test]
    fn a_test() {
        assert_eq!(1, 1);
    }
}

#[cfg(all(feature = "unstable", test))]
mod bench {
    extern crate test;
    use self::test::Bencher;

    #[bench]
    fn a_bench(b: &mut Bencher) {
        let z = b.iter(|| {
            test::black_box(|| {
                1 + 1
            })
        });
    }
}

#[cfg(all(feature = "unstable", test))]行表示仅在设置了功能且我们仍在测试模式下编译时才编译以下项目.同样,#![cfg_attr(feature = "unstable", feature(test))]仅在启用unstable功能时启用test功能标志.

The line #[cfg(all(feature = "unstable", test))] says to only compile the following item if the feature is set and we are compiling in test mode anyway. Likewise, #![cfg_attr(feature = "unstable", feature(test))] only enables the test feature flag when the unstable feature is enabled.

下面是一个例子在野外.

这篇关于使用稳定版/测试版时忽略基准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆