Skip to content

Instantly share code, notes, and snippets.

@MichaelMauderer
Created August 14, 2019 14:11
Show Gist options
  • Save MichaelMauderer/56187ad7cc29d818d5f17d3d75f1b0c1 to your computer and use it in GitHub Desktop.
Save MichaelMauderer/56187ad7cc29d818d5f17d3d75f1b0c1 to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate criterion;
use std::collections::HashSet;
use std::iter::FromIterator;
use criterion::black_box;
use criterion::Criterion;
use test::{iter_items_set, process_things_by_index_loop};
pub fn iter_items_set<'a, T>(things: &'a mut [T], indices: &[usize]) -> impl Iterator<Item=&'a mut T> {
let index_set: HashSet<usize> = HashSet::from_iter(indices.iter().cloned());
things.iter_mut().enumerate().filter_map(move |(ix, item)| {
if index_set.contains(&ix) {
Some(item)
} else { None }
})
}
pub fn process_things_by_index_loop<T>(things: &mut [T], indices: &[usize], f: &dyn Fn(&mut T)) {
for &ix in indices {
let t = &mut things[ix];
f(t);
}
}
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("loop", |b| b.iter(|| {
let mut data: Vec<i32> = (0..1500).collect();
let mut indices: Vec<usize> = (500..700).collect();
process_things_by_index_loop(black_box(&mut data), black_box(&indices), &|value| *value *= 2)
}));
c.bench_function("iter_set", |b| b.iter(|| {
let mut data: Vec<i32> = (0..1500).collect();
let mut indices: Vec<usize> = (500..700).collect();
iter_items_set(black_box(&mut data), black_box(&indices)).for_each(&|value: &mut i32| *value *= 2)
}));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment