viirya commented on code in PR #12024:
URL: https://github.com/apache/arrow-rs/pull/12024#discussion_r4447152602
##########
arrow-buffer/src/builder/boolean.rs:
##########
@@ -276,9 +276,51 @@ impl BooleanBufferBuilder {
self.advance(additional);
let offset = self.len() - additional;
- for (i, v) in slice.iter().enumerate() {
+
+ // Too short to fill a whole byte, so packing would only add overhead
+ if additional < 8 {
Review Comment:
Confirmed here too: 8-value all-false appends at offset 3 went from 28–29 µs
(7168 calls) on main to 31–35 µs at fae73df5a. Rather than an alignment-aware
cutoff, I took @mbutrovich's register packing suggestion in f00dc8db9, so the
five head values and three remainder values become two ORs. That case is now
24.6–24.9 µs, and the random one went from 170–178 µs on main (63–68 µs at
fae73df5a) to 24–25 µs. The bench now has 8-value groups at offsets 0 and 3.
##########
arrow-buffer/benches/boolean_buffer_builder.rs:
##########
@@ -0,0 +1,85 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow_buffer::BooleanBufferBuilder;
+use criterion::{BenchmarkId, Criterion, Throughput, criterion_group,
criterion_main};
+use rand::rngs::StdRng;
+use rand::{RngExt, SeedableRng};
+use std::hint;
+
+const LEN: usize = 64 * 1024;
+
+fn criterion_benchmark(c: &mut Criterion) {
+ let mut rng = StdRng::seed_from_u64(42);
+ let inputs = [
+ ("random", (0..LEN).map(|_| rng.random_bool(0.5)).collect()),
+ (
+ "mostly_true",
+ (0..LEN).map(|_| rng.random_bool(0.9)).collect(),
+ ),
+ ("all_true", vec![true; LEN]),
+ ];
+
+ let mut group = c.benchmark_group("BooleanBufferBuilder append_slice");
+ group.throughput(Throughput::Elements(LEN as u64));
+
+ for (name, values) in &inputs {
+ // An offset of 3 bits makes the slice start in the middle of a byte
+ for offset in [0, 3] {
+ let id = BenchmarkId::new(format!("offset_{offset}"), name);
+ group.bench_with_input(id, values, |b, values: &Vec<bool>| {
+ b.iter(|| {
+ let mut builder = BooleanBufferBuilder::new(offset + LEN);
+ builder.append_n(offset, true);
+ builder.append_slice(hint::black_box(values));
+ hint::black_box(builder.finish())
+ })
+ });
+ }
+ }
+
+ group.finish();
+
+ // Many appends of 1 to 7 values each, starting in the middle of a byte
+ const CALLS: usize = 7 * 1024;
+ let short_inputs = [
+ ("random", (0..8).map(|_| rng.random_bool(0.5)).collect()),
+ ("all_false", vec![false; 8]),
+ ];
+
+ let mut group = c.benchmark_group("BooleanBufferBuilder append_slice
short");
+ group.throughput(Throughput::Elements(CALLS as u64));
+
+ for (name, values) in &short_inputs {
+ group.bench_with_input(*name, values, |b, values: &Vec<bool>| {
+ b.iter(|| {
+ let mut builder = BooleanBufferBuilder::new(3 + CALLS * 4);
+ builder.append_n(3, true);
+ for i in 0..CALLS {
+ let len = i % 7 + 1;
+ builder.append_slice(hint::black_box(&values[..len]));
Review Comment:
Good catch. The repeated 28 booleans let main's per-bit branch predict well.
In f00dc8db9 the short group walks a cursor through `CALLS * 4` seeded values.
With fresh values, short/random is 76–84 µs on main, 33–36 µs at fae73df5a, and
19–20 µs now. I've updated the description to match.
##########
arrow-buffer/src/builder/boolean.rs:
##########
@@ -276,9 +276,51 @@ impl BooleanBufferBuilder {
self.advance(additional);
let offset = self.len() - additional;
- for (i, v) in slice.iter().enumerate() {
+
+ // Too short to fill a whole byte, so packing would only add overhead
+ if additional < 8 {
+ for (i, v) in slice.iter().enumerate() {
+ if *v {
+ unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(),
offset + i) }
+ }
+ }
+ } else {
+ self.pack_slice(offset, slice)
+ }
+ }
+
+ /// Writes `slice` into the already allocated bits starting at `offset`
+ ///
+ /// Kept out of line so that the short slice path of [`Self::append_slice`]
+ /// stays small when inlined
+ #[inline(never)]
+ fn pack_slice(&mut self, offset: usize, slice: &[bool]) {
+ let additional = slice.len();
+ let buffer = self.buffer.as_slice_mut();
+
+ // Set bits individually until the write position is byte aligned
+ let head = ((8 - offset % 8) % 8).min(additional);
+ let (head_slice, rest) = slice.split_at(head);
+ for (i, v) in head_slice.iter().enumerate() {
if *v {
- unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(),
offset + i) }
+ bit_util::set_bit(buffer, offset + i)
+ }
+ }
+
+ // Pack 8 bools into each byte without branching: a `bool` is a byte
+ // holding 0 or 1, and the multiply moves byte `i` to bit `56 + i`
+ let byte_offset = (offset + head) / 8;
+ let (chunks, remainder) = rest.as_chunks::<8>();
+ for (dst, chunk) in buffer[byte_offset..].iter_mut().zip(chunks) {
+ let bytes: [u8; 8] = std::array::from_fn(|i| chunk[i] as u8);
+ let packed =
u64::from_le_bytes(bytes).wrapping_mul(0x0102_0408_1020_4080) >> 56;
+ *dst = packed as u8;
+ }
+
+ let remainder_offset = self.len - remainder.len();
+ for (i, v) in remainder.iter().enumerate() {
+ if *v {
+ bit_util::set_bit(buffer, remainder_offset + i)
}
}
Review Comment:
Thanks, applied in f00dc8db9, with you as co-author. On Apple M-series,
compared with main (fae73df5a in parentheses):
- 1–7 values, random: 76–84 → 19–20 µs (33–36)
- 1–7 values, all false: 22–24 → 18 µs (19–21)
- 8 values at offset 3, random: 170–178 → 24–25 µs (63–68)
- 8 values at offset 3, all false: 28–29 → 25 µs (31–35)
- 8 values at offset 0: 22–23 µs, vs 23–25 at fae73df5a, so the head OR of 0
doesn't cost anything measurable here
The 64Ki cases are unchanged at about 1.2–1.3 µs.
`test_append_slice_offsets` covers every path (lengths 0..100 at offsets
0..16), and it fails if either the second-byte write in the short path or the
head OR is dropped.
##########
arrow-buffer/benches/boolean_buffer_builder.rs:
##########
@@ -0,0 +1,85 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow_buffer::BooleanBufferBuilder;
+use criterion::{BenchmarkId, Criterion, Throughput, criterion_group,
criterion_main};
+use rand::rngs::StdRng;
+use rand::{RngExt, SeedableRng};
+use std::hint;
+
+const LEN: usize = 64 * 1024;
+
+fn criterion_benchmark(c: &mut Criterion) {
+ let mut rng = StdRng::seed_from_u64(42);
+ let inputs = [
+ ("random", (0..LEN).map(|_| rng.random_bool(0.5)).collect()),
+ (
+ "mostly_true",
+ (0..LEN).map(|_| rng.random_bool(0.9)).collect(),
+ ),
+ ("all_true", vec![true; LEN]),
+ ];
+
+ let mut group = c.benchmark_group("BooleanBufferBuilder append_slice");
+ group.throughput(Throughput::Elements(LEN as u64));
+
+ for (name, values) in &inputs {
+ // An offset of 3 bits makes the slice start in the middle of a byte
+ for offset in [0, 3] {
+ let id = BenchmarkId::new(format!("offset_{offset}"), name);
+ group.bench_with_input(id, values, |b, values: &Vec<bool>| {
+ b.iter(|| {
+ let mut builder = BooleanBufferBuilder::new(offset + LEN);
+ builder.append_n(offset, true);
+ builder.append_slice(hint::black_box(values));
+ hint::black_box(builder.finish())
+ })
+ });
+ }
+ }
+
+ group.finish();
+
+ // Many appends of 1 to 7 values each, starting in the middle of a byte
+ const CALLS: usize = 7 * 1024;
+ let short_inputs = [
+ ("random", (0..8).map(|_| rng.random_bool(0.5)).collect()),
+ ("all_false", vec![false; 8]),
+ ];
+
+ let mut group = c.benchmark_group("BooleanBufferBuilder append_slice
short");
+ group.throughput(Throughput::Elements(CALLS as u64));
+
+ for (name, values) in &short_inputs {
+ group.bench_with_input(*name, values, |b, values: &Vec<bool>| {
+ b.iter(|| {
+ let mut builder = BooleanBufferBuilder::new(3 + CALLS * 4);
+ builder.append_n(3, true);
+ for i in 0..CALLS {
+ let len = i % 7 + 1;
+ builder.append_slice(hint::black_box(&values[..len]));
+ }
+ hint::black_box(builder.finish())
+ })
+ });
+ }
+
+ group.finish();
Review Comment:
Added as suggested in f00dc8db9.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]