问题描述
我开始使用 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),&mut matcher);
}
现在我想使用 Rust stable 作为基准。 由于 "bencher" crate 已 3 年未更新,因此 "criterion" crate 似乎是默认选项。为此,我必须将代码移动到“./benches/my_benchmark.rs”。
我怎样才能在测试和基准之间共享 block_requests(..)
?
解决方法
tests/
和 benches/
与 src/main.rs
或 src/bin/*.rs
的工作方式相同:它们是单独的二进制包。这意味着它们必须引用按名称添加到您图书馆箱子中的项目,并且这些项目必须可见。
所以,你需要改变
fn block_requests(bencher_option: Option<&mut Bencher>,...) {
使其pub
lic,并且您可能还想添加#[doc(hidden)]
,以便您的库文档不包含测试助手:
#[doc(hidden)]
pub fn block_requests(bencher_option: Option<&mut Bencher>,...) {
然后,在您的测试和基准测试中,use
通过提供您的箱子的名称。
use my_library_crate_name::block_requests;
fn bench_smth(...) {...}
(此处不能使用 use crate::block_requests
,因为关键字 crate
指的是基准二进制包,而不是库包。)