Skip to content

Commit 99825a0

Browse files
[utils] Optimize Bitmap Encoding (#3715)
1 parent c32f535 commit 99825a0

3 files changed

Lines changed: 42 additions & 6 deletions

File tree

utils/src/bitmap/benches/bench.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use criterion::criterion_main;
22

33
mod count_ones;
4+
mod write;
45

5-
criterion_main!(count_ones::benches);
6+
criterion_main!(count_ones::benches, write::benches);

utils/src/bitmap/benches/write.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use bytes::BytesMut;
2+
use commonware_codec::{EncodeSize, Write};
3+
use commonware_utils::bitmap::BitMap;
4+
use criterion::{criterion_group, Criterion};
5+
use std::hint::black_box;
6+
7+
fn bench_write<const CHUNK_SIZE: usize>(c: &mut Criterion, size: u64) {
8+
let bitmap = BitMap::<CHUNK_SIZE>::ones(size);
9+
let encoded_size = bitmap.encode_size();
10+
let mut buf = BytesMut::with_capacity(encoded_size);
11+
12+
c.bench_function(
13+
&format!("{}/size={size} chunk_size={CHUNK_SIZE}", module_path!()),
14+
|b| {
15+
b.iter(|| {
16+
buf.clear();
17+
black_box(&bitmap).write(&mut buf);
18+
black_box(buf.len());
19+
});
20+
},
21+
);
22+
}
23+
24+
fn benchmark_write(c: &mut Criterion) {
25+
for size in [64, 1 << 10, 1 << 14, 1 << 18, 1 << 22, 1 << 26] {
26+
bench_write::<4>(c, size);
27+
bench_write::<8>(c, size);
28+
bench_write::<16>(c, size);
29+
bench_write::<32>(c, size);
30+
}
31+
}
32+
33+
criterion_group! {
34+
name = benches;
35+
config = Criterion::default().sample_size(10);
36+
targets = benchmark_write,
37+
}

utils/src/bitmap/mod.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -844,11 +844,9 @@ impl<const N: usize> Write for BitMap<N> {
844844
self.len().write(buf);
845845

846846
// Write all chunks
847-
for chunk in &self.chunks {
848-
for &byte in chunk {
849-
byte.write(buf);
850-
}
851-
}
847+
let (front, back) = self.chunks.as_slices();
848+
buf.put_slice(front.as_flattened());
849+
buf.put_slice(back.as_flattened());
852850
}
853851
}
854852

0 commit comments

Comments
 (0)