jeudi 11 février 2021

How can one share the code between tests and benches in Rust?

I started writing benchmarks in Rust with "bench" and Rust nightly as written in the docs.

In order to share the code between test and benchmarks i've added Option<&mut Bencher> and either run the code block directly or with bencher passed ("src/lib.rs"):

fn block_requests(bencher_option: Option<&mut Bencher>, ...) {
    ...

    let mut block = || {
       ... // shared
    }

    match bencher_option {
            // regular test
            None => block(),

            // benchmark
            Some(bencher) => {
                bencher.iter(block);
            }
        }
    ...
}

// call from test
#[test]
fn test_smth() {
    block_requests(None, &requests, &mut matcher);
}


// call from benchmark
#[bench]
fn bench_smth(b: &mut Bencher) {
    block_requests(Some(b), &requests, &mut matcher);
}

Now i want to use Rust stable for benchmarks. Since "bencher" crate is not updated for 3 years it seems that "criterion" crate is the default option. For this i have to move the code to "./benches/my_benchmark.rs".

How can i still share the block_requests(..) between the tests and benchmarks?

Aucun commentaire:

Enregistrer un commentaire