Rust Criterion benchmarking modules `unresolved import `crate::some_module``

Viewed 777

I have a binary project with a lot of internal modules to organise functionality.

I'm trying to get Criterion working for benchmarks.

The error:

error[E0432]: unresolved import `crate::some_module`
 --> benches/benchmarks.rs:3:5
  |
3 | use crate::some_module;
  |     ^^^^^^^^^^^^^^^^^^ no `some_module` in the root

error: aborting due to previous error

Minimal example .zip: https://drive.google.com/file/d/1TASKI9_ODJniamHp3RBRscoflabPT-kP/view?usp=sharing

My current minimal example looks like:

.
├── Cargo.lock
├── Cargo.toml
├── src/
│   ├── main.rs
│   └── some_module/
│       ├── mod.rs
│       └── some_module_file.rs
└── benches/
    └── benchmarks.rs

Cargo.toml:

[package]
name = "criterion-bin-test"
version = "0.1.0"
authors = ["Jonathan <jonthanwoollettlight@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[dev-dependencies]
criterion = "0.3"

[[bench]]
name = "benchmarks"
harness = false

main.rs:

mod some_module;

fn main() {
    println!("Hello, world!");

    println!("{}",some_module::some_mod_file::two());
}

mod.rs:

pub mod some_mod_file;

some_module_file:

pub fn two() -> i32 {
    2
}

benchmarks.rs:

use criterion::{black_box, criterion_group, criterion_main, Criterion};

use crate::some_module;

fn fibonacci(n: u64) -> u64 {
    match n {
        0 => 1,
        1 => 1,
        n => fibonacci(n-1) + fibonacci(n-2),
    }
}

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

The error arises on use crate::some_module, and I cannot figure out how to apply Criterion benchmarks to internal module. Would really appreciate any help here.

Tests in my current project are handled as:

.
├── Cargo.lock
├── Cargo.toml
├── src/
|   ├── main.rs
.   ├── tests.rs
    . some_module/
        ├── mod.rs
        ├── tests.rs
        .

Which allows for use crate::some_module.

1 Answers

for anyone struggling with this issue.

When implementing benchmarks (or examples), if we want to include some of our modules/functions, we have to do it the same way we would if we were including those from our already installed package.

For instance, in the question above there is an error indicating that:

error[E0432]: unresolved import `crate::some_module`
 --> benches/benchmarks.rs:3:5
  |
3 | use crate::some_module;
  |     ^^^^^^^^^^^^^^^^^^ no `some_module` in the root

error: aborting due to previous error

That's because it should read like:

use criterion-bin-test::some_module;

Where criterion-bin-test is the actual package name, use that instead of crate:: when implementing examples or benchmarks;

Related