use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use iterstats::Iterstats; use rand::seq::IteratorRandom; use std::hint::black_box; fn naive<'a>(iter: impl Iterator + Clone) -> f64 { let sum = iter.clone().sum::(); let count = iter.count() as f64; sum / count } fn bench_mean(c: &mut Criterion) { let mut group = c.benchmark_group("mean"); let mut rng = &mut rand::thread_rng(); for len in [10, 100, 1000, 10000, 100_000, 1_000_000] { let data = (0..2 * len) .map(|i| i as f64) .choose_multiple(&mut rng, len); assert_eq!(data.len(), len); group.bench_with_input(BenchmarkId::new("naive", len), &data, |b, i| { b.iter(|| black_box(naive(black_box(i.iter())))) }); group.bench_with_input(BenchmarkId::new("iterstats", len), &data, |b, i| { b.iter(|| black_box(black_box(i.iter()).mean())) }); } group.finish(); } criterion_group!(benches, bench_mean); criterion_main!(benches);