Skip to content

Commit 992305a

Browse files
committed
bench for q460_lfu_cache to compare different implementations
1 parent 392b89c commit 992305a

File tree

2 files changed

+78
-1
lines changed

2 files changed

+78
-1
lines changed

implementations/q460_lfu_cache/Cargo.toml

+8-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,11 @@ intrusive-collections = "0.9.7"
99

1010
[dev-dependencies]
1111
rstest = "0.23.0"
12-
proptest = "1.5.0"
12+
proptest = "1.5.0"
13+
once_cell = "1.20.2"
14+
rand = "0.8.5"
15+
criterion = "0.5.1"
16+
17+
[[bench]]
18+
name = "bench_all_impl"
19+
harness = false # Disables the default Rust benchmarking harness so that Criterion can use its own.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
use criterion::{black_box, criterion_group, criterion_main, Criterion};
2+
use once_cell::sync::Lazy;
3+
use rand::rngs::StdRng;
4+
use rand::{Rng, SeedableRng};
5+
6+
const SEED: u64 = 12345; // Use a fixed seed for reproducibility
7+
8+
static OPERATIONS: Lazy<Vec<(u8, i32, i32)>> = Lazy::new(|| {
9+
// Generate random data here
10+
let mut rng = StdRng::seed_from_u64(SEED);
11+
12+
let num_operations = 2000; // Set the number of operations
13+
let mut operations = Vec::with_capacity(num_operations);
14+
15+
for _ in 0..num_operations {
16+
let op = rng.gen_range(0..2) as u8; // 0 for put, 1 for get
17+
let key = rng.gen_range(0..=100_000i32);
18+
let value = rng.gen_range(0..=1_000_000_000i32); // Only needed for put operations
19+
operations.push((op, key, value));
20+
}
21+
22+
operations
23+
});
24+
25+
use q460_lfu_cache::impl_v1::LFUCache as LFUCache_v1;
26+
use q460_lfu_cache::impl_v2::LFUCache as LFUCache_v2;
27+
use q460_lfu_cache::impl_v3::LFUCache as LFUCache_v3;
28+
use q460_lfu_cache::impl_v4::LFUCache as LFUCache_v4;
29+
30+
macro_rules! bench_lfu_cache {
31+
($bench_name:ident, $cache_type:ty) => {
32+
fn $bench_name(c: &mut Criterion) {
33+
// Define the capacity as a constant or parameter
34+
const CAPACITY: i32 = 10_000i32;
35+
36+
c.bench_function(stringify!($bench_name), |b| {
37+
b.iter(|| {
38+
let mut cache: $cache_type = <$cache_type>::new(black_box(CAPACITY));
39+
for &(op, key, value) in OPERATIONS.iter() {
40+
match op {
41+
0 => {
42+
// Put operation
43+
cache.put(black_box(key), black_box(value));
44+
}
45+
1 => {
46+
// Get operation
47+
black_box(cache.get(black_box(key)));
48+
}
49+
_ => unreachable!(),
50+
}
51+
}
52+
})
53+
});
54+
}
55+
};
56+
}
57+
58+
bench_lfu_cache!(bench_lfu_cache_v1, LFUCache_v1);
59+
bench_lfu_cache!(bench_lfu_cache_v2, LFUCache_v2);
60+
bench_lfu_cache!(bench_lfu_cache_v3, LFUCache_v3);
61+
bench_lfu_cache!(bench_lfu_cache_v4, LFUCache_v4);
62+
63+
criterion_group!(
64+
benches,
65+
bench_lfu_cache_v1,
66+
bench_lfu_cache_v2,
67+
bench_lfu_cache_v3,
68+
bench_lfu_cache_v4,
69+
);
70+
criterion_main!(benches);

0 commit comments

Comments
 (0)