Search code examples
rustrust-criterion

Is it possible to limit the number of iterations that Criterion performs?


I am developing some benchmarks for a crate using criterion (cargo bench). I would like to temporarily limit the amount of iterations until I finish the code.

I know measurements may not be precise, but this is just temporary. Is this possible?


Solution

  • It is possible.

    Look at the Criterion Benchmark. There you can find methods relevant to you, specifically measurement_time .

    Digging deeper, you can find how to use them here:

    fn bench(c: &mut Criterion) {
        // Setup (construct data, allocate memory, etc)
        c.bench(
            "routines",
            Benchmark::new("routine_1", |b| b.iter(|| routine_1()))
                .with_function("routine_2", |b| b.iter(|| routine_2()))
                .measurement_time(Duration::from_millis(1000))
        );
    }
    
    criterion_group!(benches, bench);
    criterion_main!(benches);
    

    Where measurement_time(Duration::from_millis(1000)) is the droid you're looking for. This effectively dropped the number of iterations for my specific function by 80%.