【发布时间】:2021-12-01 00:42:16
【问题描述】:
我正在使用 Criterion 运行基准测试,但在输入未实现 Copy 特征的函数时遇到问题。
例如,我为签名为pub fn hash(vector: Vec<&str>) -> u64 的函数设置了以下基准。
pub fn criterion_benchmark(c: &mut Criterion) {
let s: String = String::from("Hello World!");
let tokens: Vec<&str> = hashing::tokenize(&s);
c.bench_function(
"hash",
|b| b.iter(|| {
hashing::hash(tokens)
}),
);
}
但是,与具有 Copy 特征的类型不同,编译器会抛出以下所有权错误。
error[E0507]: cannot move out of `tokens`, a captured variable in an `FnMut` closure
--> benches/benchmark.rs:17:34
|
13 | let tokens: Vec<&str> = hashing::tokenize(&s);
| ------ captured outer variable
...
17 | hashing::hash(tokens)
| ^^^^^^ move occurs because `tokens` has type `Vec<&str>`, which does not implement the `Copy` trait
error[E0507]: cannot move out of `tokens`, a captured variable in an `FnMut` closure
--> benches/benchmark.rs:16:20
|
13 | let tokens: Vec<&str> = hashing::tokenize(&s);
| ------ captured outer variable
...
16 | |b| b.iter(|| {
| ^^ move out of `tokens` occurs here
17 | hashing::hash(tokens)
| ------
| |
| move occurs because `tokens` has type `Vec<&str>`, which does not implement the `Copy` trait
| move occurs due to use in closure
如何将不可复制的输入传递给基准函数而不遇到所有权问题?
【问题讨论】:
-
真正的问题似乎出在基准哈希函数中。您不能将其修复为接受
&[&str](并使用hashing::hash(&tokens)调用它)吗?为什么散列需要一个 vec ? -
为什么不克隆它?
-
@Stargateur 克隆参数解决了这个问题。谢谢!
-
@Stargateur 克隆向量的开销会影响基准测试吗?
-
@Stargateur @DenysSéguret 结果:与接受
&[&str]相比,克隆函数的开销约为 50%。
标签: rust ownership rust-criterion