|
| 1 | +use criterion::{criterion_group, criterion_main, Criterion}; |
| 2 | +use rand::prelude::*; |
| 3 | +use std::collections::HashSet; |
| 4 | + |
| 5 | +const SIZE: usize = 10000; |
| 6 | + |
| 7 | +/// This benchmark compares the performance of HashSet, Vob, and Vec |
| 8 | +/// in a scenario where an algorithm needs to keep track of visited indices. |
| 9 | +#[cfg(test)] |
| 10 | +fn comparative(c: &mut Criterion) { |
| 11 | + // Generate 10000 random (seeded) points |
| 12 | + let mut rng: StdRng = SeedableRng::from_seed([42; 32]); |
| 13 | + let mut indices: Vec<usize> = (0..SIZE).collect(); |
| 14 | + |
| 15 | + indices.shuffle(&mut rng); |
| 16 | + |
| 17 | + c.bench_function("HashSet comparative", |b| { |
| 18 | + b.iter(|| { |
| 19 | + let mut hash_set = HashSet::new(); |
| 20 | + // set half of the set to "true" |
| 21 | + for index in indices.iter().skip(SIZE / 2) { |
| 22 | + hash_set.insert(index); |
| 23 | + } |
| 24 | + |
| 25 | + for index in indices.iter().take(SIZE / 2) { |
| 26 | + assert!( |
| 27 | + !hash_set.contains(index), |
| 28 | + "index {} is supposed to be cleared", |
| 29 | + index |
| 30 | + ); |
| 31 | + } |
| 32 | + for index in indices.iter().skip(SIZE / 2) { |
| 33 | + assert!( |
| 34 | + hash_set.contains(index), |
| 35 | + "index {} is supposed to be set", |
| 36 | + index |
| 37 | + ); |
| 38 | + } |
| 39 | + }) |
| 40 | + }); |
| 41 | + |
| 42 | + c.bench_function("Vob comparative", |b| { |
| 43 | + b.iter(|| { |
| 44 | + let mut vob: vob::Vob<u32> = vob::Vob::new_with_storage_type(SIZE); |
| 45 | + vob.resize(SIZE, false); |
| 46 | + |
| 47 | + // set half of the vob to true |
| 48 | + for index in indices.iter().skip(SIZE / 2) { |
| 49 | + vob.set(*index, true); |
| 50 | + } |
| 51 | + |
| 52 | + for index in indices.iter().take(SIZE / 2) { |
| 53 | + assert!(!vob[*index], "index {} is supposed to be cleared", index); |
| 54 | + } |
| 55 | + for index in indices.iter().skip(SIZE / 2) { |
| 56 | + assert!(vob[*index], "index {} is supposed to be set", index); |
| 57 | + } |
| 58 | + }) |
| 59 | + }); |
| 60 | + |
| 61 | + c.bench_function("Vec comparative", |b| { |
| 62 | + b.iter(|| { |
| 63 | + let mut vec: Vec<bool> = vec![false; SIZE]; |
| 64 | + |
| 65 | + // set half of the vec to true |
| 66 | + for index in indices.iter().skip(SIZE / 2) { |
| 67 | + vec[*index] = true; |
| 68 | + } |
| 69 | + |
| 70 | + for index in indices.iter().take(SIZE / 2) { |
| 71 | + assert!(!vec[*index], "index {} is supposed to be cleared", index); |
| 72 | + } |
| 73 | + for index in indices.iter().skip(SIZE / 2) { |
| 74 | + assert!(vec[*index], "index {} is supposed to be set", index); |
| 75 | + } |
| 76 | + }) |
| 77 | + }); |
| 78 | +} |
| 79 | + |
| 80 | +criterion_group!(benches, comparative); |
| 81 | +criterion_main!(benches); |
0 commit comments