我的项目的路径结构如下:
demo
├── benches
│ └── crypto_bench.rs
├── src
│ ├── main.rs
│ └── crypto.rs
├── Cargo.lock
└── Cargo.toml
crypto.rs
包含一个带有实现的结构Crypto
。 crypto.rs
是使用main.rs
从mod crypto;
提到的
如何在长凳文件夹中使用crypto.rs
的crypto_bench.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() {}
}
然后从基准和二进制文件中导入您的库:
长凳/ 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 /斌/ 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
也可以看看: