如何在每个文件的基础上执行`货物工作台?

时间:2018-05-03 16:45:17

标签: rust benchmarking rust-cargo

我正在解决Project Euler个问题,我将每个问题都放在另一个文件中。当我尝试针对每个问题采用不同的方法时,我会在各自的文件中为每个问题创建一系列基准。

我的目录结构如下:

euler/
    Cargo.lock
    Cargo.toml
    README.md
    src/
        main.rs
        p001.rs
        p002.rs
        ...etc.

main.rs的内容是:

#![feature(test)]

extern crate primes;
extern crate test;

mod p001;
mod p002;
// ... etc

fn main() {}

当我运行cargo bench时,它会为我项目中的每个文件运行基准测试:

$ cargo bench
    Finished release [optimized] target(s) in 0.02 secs
     Running target/release/deps/euler_rust-5be87dff38a04da2

running 11 tests
test p001::bench_fold_sum                     ... bench:      12,955 ns/iter (+/- 13,501)
test p001::bench_for_sum                      ... bench:      11,385 ns/iter (+/- 7,383)
test p002::bench_for_sum                      ... bench:         270 ns/iter (+/- 90)
test p002::bench_takewhile_filter_mutable_sum ... bench:         322 ns/iter (+/- 333)
test p002::bench_takewhile_filter_sum         ... bench:         512 ns/iter (+/- 379)
test p002::bench_takewhile_sum                ... bench:         273 ns/iter (+/- 117)
test p002::bench_while_sum                    ... bench:         286 ns/iter (+/- 240)

我只对运行一个文件中包含的基准测试感兴趣,但在cargo bench之后指定文件名会产生以下结果:

$ cargo bench src/p002.rs
    Finished release [optimized] target(s) in 0.02 secs
     Running target/release/deps/euler_rust-5be87dff38a04da2

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 11 filtered out

如何在单个文件中运行基准测试?

1 个答案:

答案 0 :(得分:5)

没有直接"在磁盘上运行此文件中包含的测试"选项。 cargo bench的帮助说:

$ cargo bench --help
Execute all benchmarks of a local package

Usage:
    cargo bench [options] [BENCHNAME] [--] [<args>...]

Options:
    BENCHNAME                    If specified, only run benches containing this string in their names

此外,文件对应于Rust模块,模块是测试名称的一部分。

您可以将这两个内容组合在一起,并使用cargo bench my_file_slash_module_name来限制运行的测试。在您的具体情况下:

cargo bench p002

如果您碰巧有其他测试或模块包含相同的子字符串,您有时可以通过添加冒号来逃避:

cargo bench p002::