这是字面上的答案,但是实际上不使用这个!
#![feature(test)]
extern crate test;
#[path = "../src/foo.rs"] // Here
mod foo;
#[bench]
fn bencher(_: &mut test::Bencher) {
println!("{:?}", foo::Thang);
}
事实上,这很可能行不通,因为你的代码foo.rs
需要来自其他不会包含的文件的支持代码。
而不是这样做,只需创建一个库。您拥有库的纯粹定义 - 一段想要在两个不同的可执行文件中使用的代码。您不必放弃可执行文件,甚至不必创建单独的目录(请参阅Rust 包同时包含库和二进制文件? https://stackoverflow.com/q/26946646/155423),但创建可重用代码是制作的关键组成部分good code.
你的最终状态看起来像:
demo
├── Cargo.lock
├── Cargo.toml
├── benches
│ └── crypto_bench.rs
├── benchmarks
└── src
├── bin
│ └── main.rs
├── crypto.rs
└── lib.rs
将可重用代码移至库:
src/lib.rs
pub mod crypto;
src/crypto.rs
pub struct Crypto;
impl Crypto {
pub fn secret() {}
}
然后从基准测试和二进制文件中导入您的库:
长凳/crypto_bench.rs
#![feature(test)]
extern crate test;
use demo::crypto::Crypto;
use test::Bencher;
#[bench]
fn speedy(b: &mut Bencher) {
b.iter(|| Crypto::secret());
}
src/bin/main.rs
use demo::crypto::Crypto;
fn main() {
Crypto::secret();
eprintln!("Did the secret thing!");
}
然后您可以通过不同的方式运行它:
$ cargo build
Compiling demo v0.1.0 (/private/tmp/example)
Finished dev [unoptimized + debuginfo] target(s) in 0.51s
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/main`
Did the secret thing!
$ cargo +nightly bench
Compiling demo v0.1.0 (/private/tmp/example)
Finished release [optimized] target(s) in 0.70s
Running target/release/deps/my_benchmark-5c9c5716763252a0
running 1 test
test speedy ... bench: 1 ns/iter (+/- 0)
test result: ok. 0 passed; 0 failed; 0 ignored; 1 measured; 0 filtered out
也可以看看:
- Rust 包同时包含库和二进制文件? https://stackoverflow.com/q/26946646/155423
- 为集成测试和基准测试提供共享实用函数的惯用方法是什么? https://stackoverflow.com/q/44539729/155423
- 我可以公开对象仅用于集成测试和/或基准测试吗? https://stackoverflow.com/q/47698194/155423
- 无法在集成测试中导入模块 https://stackoverflow.com/q/46867652/155423