use std::collections::HashMap; use binggan::{black_box, plugins::*, BenchRunner, PeakMemAlloc, INSTRUMENTED_SYSTEM}; #[global_allocator] pub static GLOBAL: &PeakMemAlloc = &INSTRUMENTED_SYSTEM; fn test_vec(data: &Vec) -> Vec { let mut vec = Vec::new(); for idx in data { if vec.len() <= *idx { vec.resize(idx + 1, 0); } vec[*idx] += 1; } vec } fn test_hashmap(data: &Vec) -> HashMap { let mut map = std::collections::HashMap::new(); for idx in data { *map.entry(*idx).or_insert(0) += 1; } map } fn run_bench() { let inputs: Vec<(&str, Vec)> = vec![ ( "max id 100; 100 el all the same", std::iter::repeat(100).take(100).collect(), ), ("max id 100; 100 el all different", (0..100).collect()), ]; let mut runner: BenchRunner = BenchRunner::new(); runner .add_plugin(CacheTrasher::default()) .add_plugin(PeakMemAllocPlugin::new(GLOBAL)) .add_plugin(PerfCounterPlugin::default()); for (input_name, data) in inputs.iter() { let mut group = runner.new_group(); group.set_name(input_name); group.set_input_size(data.len() * std::mem::size_of::()); group.register_with_input("vec", data, move |data| { let vec = black_box(test_vec(data)); vec.len() as u64 }); group.register_with_input("hashmap", data, move |data| { let map = black_box(test_hashmap(data)); map.len() as u64 * (std::mem::size_of::() + std::mem::size_of::()) as u64 }); group.run(); } } fn main() { run_bench(); }