【问题标题】:How can one share the code between tests and benches in Rust?如何在 Rust 中的测试和工作台之间共享代码?
【发布时间】:2021-05-15 03:38:45
【问题描述】:

我开始在 Rust 中使用“bench”和 Rust nightly 编写基准测试,如文档中所述。

为了在测试和基准测试之间共享代码,我添加了 Option<&mut Bencher> 并直接运行代码块或通过 bencher ("src/lib.rs") 运行代码块:

fn block_requests(bencher_option: Option<&mut Bencher>, ...) {
    ...

    let mut block = || {
       ... // shared
    }

    match bencher_option {
            // regular test
            None => block(),

            // benchmark
            Some(bencher) => {
                bencher.iter(block);
            }
        }
    ...
}

// call from test
#[test]
fn test_smth() {
    block_requests(None, &requests, &mut matcher);
}


// call from benchmark
#[bench]
fn bench_smth(b: &mut Bencher) {
    block_requests(Some(b), &requests, &mut matcher);
}

现在我想使用 Rust stable 进行基准测试。 由于"bencher" crate 3 年未更新,因此"criterion" crate 似乎是默认选项。为此,我必须将代码移动到“./benches/my_benchmark.rs”。

我怎样才能在测试和基准测试之间共享block_requests(..)

【问题讨论】:

  • use mycrate::block_requests

标签: testing rust benchmarking source-sets


【解决方案1】:

tests/benches/src/main.rssrc/bin/*.rs 的工作方式相同:它们是独立的二进制 crate。 这意味着它们必须按名称引用库 crate 中的项目,并且这些项目必须是可见的。

所以,你需要改变

fn block_requests(bencher_option: Option<&mut Bencher>, ...) {

要使其成为public,您可能还需要添加#[doc(hidden)],以便您的库文档不包含测试助手:

#[doc(hidden)]
pub fn block_requests(bencher_option: Option<&mut Bencher>, ...) {

然后,在您的测试和基准测试中,use提供您的 crate 的名称。

use my_library_crate_name::block_requests;

fn bench_smth(...) {...}

(您不能在此处使用use crate::block_requests,因为关键字crate 指的是基准二进制包,而不是库包。)

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2020-03-03
    • 2020-09-13
    相关资源
    最近更新 更多