|
| 1 | +use super::{Digest, DummyMetrics}; |
| 2 | +use commonware_cryptography::{Hasher, Sha256}; |
| 3 | +use commonware_storage::{ |
| 4 | + index::{unordered, Unordered}, |
| 5 | + translator::{EightCap, FourCap, OneCap, Translator, TwoCap}, |
| 6 | +}; |
| 7 | +use criterion::{criterion_group, Criterion}; |
| 8 | +use rand::{rngs::StdRng, seq::SliceRandom, SeedableRng}; |
| 9 | +use std::{ |
| 10 | + hint::black_box, |
| 11 | + time::{Duration, Instant}, |
| 12 | +}; |
| 13 | + |
| 14 | +#[cfg(not(full_bench))] |
| 15 | +const N_ITEMS: [usize; 2] = [10_000, 50_000]; |
| 16 | +#[cfg(full_bench)] |
| 17 | +const N_ITEMS: [usize; 5] = [10_000, 50_000, 100_000, 500_000, 1_000_000]; |
| 18 | + |
| 19 | +fn run_lookup<T: Translator>( |
| 20 | + c: &mut Criterion, |
| 21 | + translator: T, |
| 22 | + name: &str, |
| 23 | + items: usize, |
| 24 | + keys: &[Digest], |
| 25 | +) { |
| 26 | + // Populate the index |
| 27 | + let mut index = unordered::Index::new(DummyMetrics, translator); |
| 28 | + for (i, key) in keys.iter().enumerate().take(items) { |
| 29 | + index.insert(key, i as u64); |
| 30 | + } |
| 31 | + |
| 32 | + // Shuffle lookup order |
| 33 | + let mut rng = StdRng::seed_from_u64(1); |
| 34 | + let mut lookup_keys: Vec<_> = keys.iter().take(items).cloned().collect(); |
| 35 | + lookup_keys.shuffle(&mut rng); |
| 36 | + |
| 37 | + let label = format!("{}/translator={name} items={items}", module_path!()); |
| 38 | + c.bench_function(&label, |b| { |
| 39 | + b.iter_custom(|iters| { |
| 40 | + let mut total = Duration::ZERO; |
| 41 | + for _ in 0..iters { |
| 42 | + let start = Instant::now(); |
| 43 | + for key in &lookup_keys { |
| 44 | + black_box(index.get(key).next().is_some()); |
| 45 | + } |
| 46 | + total += start.elapsed(); |
| 47 | + } |
| 48 | + total |
| 49 | + }); |
| 50 | + }); |
| 51 | +} |
| 52 | + |
| 53 | +fn bench_lookup(c: &mut Criterion) { |
| 54 | + let max_items = *N_ITEMS.last().unwrap(); |
| 55 | + let keys: Vec<_> = (0..max_items) |
| 56 | + .map(|i| Sha256::hash(&i.to_be_bytes())) |
| 57 | + .collect(); |
| 58 | + |
| 59 | + for items in N_ITEMS { |
| 60 | + run_lookup(c, OneCap, "one_cap", items, &keys); |
| 61 | + run_lookup(c, TwoCap, "two_cap", items, &keys); |
| 62 | + run_lookup(c, FourCap, "four_cap", items, &keys); |
| 63 | + run_lookup(c, EightCap, "eight_cap", items, &keys); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +criterion_group! { |
| 68 | + name = benches; |
| 69 | + config = Criterion::default().sample_size(10); |
| 70 | + targets = bench_lookup, |
| 71 | +} |
0 commit comments