You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust库基准测试的项目结构放置位置及cargo bench运行失败咨询

Rust库基准测试的正确项目位置

Great question! Let's break this down clearly—Rust's benchmarking setup has specific conventions that are easy to miss if you're used to putting tests in the tests directory.

核心结论:基准测试默认放在benches目录

Cargo reserves a dedicated benches directory (at your project root, alongside src and tests) for benchmarking code. This is separate from the tests directory, which is intended for integration tests—Cargo treats these two directories differently by default, which is why your benchmarks in tests aren't running with cargo bench.

Step-by-Step Setup

  1. Create the benches directory
    Make a new folder at your project root named benches—your project structure should look like this:

    your_crate/
    ├── src/
    ├── tests/
    ├── benches/  # 新建这个目录
    └── Cargo.toml
    
  2. Write your benchmark code
    Inside benches, create a .rs file (e.g., core_benchmarks.rs). Most Rust developers use the criterion crate (a robust, widely-used benchmarking library) instead of the standard library's basic #[bench] attribute. Here's a quick example:

    use criterion::{criterion_group, criterion_main, Criterion};
    use your_crate::your_function; // 导入你要测试的库函数
    
    fn bench_your_function(c: &mut Criterion) {
        // 定义基准测试:测试your_function的性能
        c.bench_function("your_function_with_input_42", |b| {
            b.iter(|| your_function(42))
        });
    }
    
    // 组织测试组并指定入口
    criterion_group!(benches, bench_your_function);
    criterion_main!(benches);
    
  3. Add the criterion dependency
    Update your Cargo.toml to include criterion as a dev dependency:

    [dev-dependencies]
    criterion = "0.5" # 替换为最新版本号即可
    
  4. Run the benchmarks
    Execute the standard benchmark command:

    cargo bench
    

    Cargo will automatically compile and run all benchmarks in the benches directory.

What if I really want benchmarks in the tests directory?

While not the recommended approach, you can force Cargo to treat a test file as a benchmark by adding a configuration to Cargo.toml:

[[test]]
name = "my_test_file" # 替换成你tests目录里的文件名(不含.rs)
bench = true

Then run it with:

cargo bench --test my_test_file

But this is clunky compared to using the dedicated benches directory, which is the community standard.

内容的提问来源于stack exchange,提问作者Steve Klabnik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:11:33