|
| 1 | +use std::{ |
| 2 | + hash::{DefaultHasher, Hash}, |
| 3 | + hint::black_box, |
| 4 | + time::Duration, |
| 5 | +}; |
| 6 | + |
| 7 | +use consistent_hashing::{ConsistentChooseKHasher, ConsistentHasher}; |
| 8 | +use criterion::{ |
| 9 | + criterion_group, criterion_main, AxisScale, Bencher, BenchmarkId, Criterion, PlotConfiguration, |
| 10 | + Throughput, |
| 11 | +}; |
| 12 | +use rand::{rng, Rng}; |
| 13 | + |
| 14 | +fn throughput_benchmark(c: &mut Criterion) { |
| 15 | + let keys: Vec<u64> = rng().random_iter().take(1000).collect(); |
| 16 | + |
| 17 | + let mut group = c.benchmark_group(format!("choose")); |
| 18 | + group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)); |
| 19 | + for n in [1usize, 10, 100, 1000, 10000] { |
| 20 | + group.throughput(Throughput::Elements(keys.len() as u64)); |
| 21 | + group.bench_with_input(BenchmarkId::new(format!("1"), n), &n, |b, n| { |
| 22 | + b.iter_batched( |
| 23 | + || &keys, |
| 24 | + |keys| { |
| 25 | + for key in keys { |
| 26 | + let mut h = DefaultHasher::new(); |
| 27 | + key.hash(&mut h); |
| 28 | + black_box(ConsistentHasher::new(h).prev(*n + 1)); |
| 29 | + } |
| 30 | + }, |
| 31 | + criterion::BatchSize::SmallInput, |
| 32 | + ) |
| 33 | + }); |
| 34 | + for k in [1, 2, 3, 10, 100] { |
| 35 | + group.bench_with_input(BenchmarkId::new(format!("k_{k}"), n), &n, |b, n| { |
| 36 | + b.iter_batched( |
| 37 | + || &keys, |
| 38 | + |keys| { |
| 39 | + let mut res = Vec::with_capacity(k); |
| 40 | + for key in keys { |
| 41 | + let mut h = DefaultHasher::new(); |
| 42 | + key.hash(&mut h); |
| 43 | + black_box(ConsistentChooseKHasher::new(h, k).prev(*n + k, &mut res)); |
| 44 | + } |
| 45 | + }, |
| 46 | + criterion::BatchSize::SmallInput, |
| 47 | + ) |
| 48 | + }); |
| 49 | + } |
| 50 | + } |
| 51 | + group.finish(); |
| 52 | +} |
| 53 | + |
| 54 | +criterion_group!( |
| 55 | + name = benches; |
| 56 | + config = Criterion::default() |
| 57 | + .warm_up_time(Duration::from_millis(500)) |
| 58 | + .measurement_time(Duration::from_millis(4000)) |
| 59 | + .nresamples(1000); |
| 60 | + |
| 61 | + targets = throughput_benchmark, |
| 62 | +); |
| 63 | +criterion_main!(benches); |
0 commit comments