我的项目路径结构如下:
demo
├── benches
│ └── crypto_bench.rs
├── src
│ ├── main.rs
│ └── crypto.rs
├── Cargo.lock
└── Cargo.toml
crypto.rs
包含一个带有实现的结构 Crypto
。
crypto.rs
使用 mod crypto;
main.rs
引用
如何使用 benches 文件夹内 crypto_bench.rs
中的 crypto.rs
?
我已经尝试了 extern crate
、mod
、super
和 use
的各种变体。
我可以在网上找到的所有示例都是针对带有 lib.rs
的库项目,而当使用带有 main.rs
文件的项目时,这些“导入”不起作用。
最佳答案
这是字面上的答案,但不要实际使用它!
#![feature(test)]
extern crate test;
#[path = "../src/foo.rs"] // Here
mod foo;
#[bench]
fn bencher(_: &mut test::Bencher) {
println!("{:?}", foo::Thang);
}
事实上,这很可能行不通,因为您在 foo.rs
中的代码需要来自其他文件的支持代码,而这些代码不会被包含在内。
不用这样做,只需创建一个库。您拥有库的纯粹定义 - 一段要在两个不同的可执行文件中使用的代码。您不必放弃拥有可执行文件,甚至不必创建单独的目录(请参阅 Rust package with both a library and a binary? ),但创建可重用代码是制作好代码的关键组成部分。
你的最终状态看起来像这样:
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() {}
}
然后从基准和二进制导入你的库:
benches/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 - 如何在二进制项目中使用 src 文件夹外部的模块,例如用于集成测试或基准测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55481089/