use std::hint::black_box; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use iterstats::Iterstats; use rand::seq::IteratorRandom; fn naive<'a>(iter: impl Iterator + Clone, min: f64, max: f64) -> Vec { let datamin = iter .clone() .min_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap(); let datamax = iter .clone() .max_by(|a, b| a.partial_cmp(b).unwrap()) .unwrap(); let datarange = datamax - datamin; let normrange = max - min; iter.map(|i| (i - datamin) / datarange * normrange + min) .collect() } fn bench_normalize(c: &mut Criterion) { let mut group = c.benchmark_group("normalize"); 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()), black_box(0.), black_box(1.)))) }); group.bench_with_input(BenchmarkId::new("iterstats", len), &data, |b, i| { b.iter(|| { black_box( black_box(black_box(i.iter()).normalize(black_box(0.), black_box(1.))) .collect::>(), ) }) }); } group.finish(); } criterion_group!(benches, bench_normalize); criterion_main!(benches);