ariel-miculas commented on PR #12423:
URL: https://github.com/apache/arrow-rs/pull/12423#issuecomment-7107559001
I didn't include the counting allocator code, I'm pasting it below
`arrow-ipc/examples/count_decode_allocations.rs`:
```
//! Counts every heap allocation made while reading an IPC stream.
//!
//! Run with:
//!
//! ```text
//! cargo run --release --example count_decode_allocations --features
lz4,zstd
//! ```
//!
//! A `#[global_allocator]` wrapping [`System`] sees every allocation the
process makes -- this
//! crate's, its dependencies', and `std`'s -- so what this prints is a
census rather than a
//! profiler's sample, and the figures come out as exact integers. That
makes it the right
//! instrument for a question a flamegraph cannot answer: *how many*
allocations, and of what
//! size, does decoding a message cost?
//!
//! Three details matter for reading the output:
//!
//! - `realloc` counts as one allocation and contributes only its growth.
This is load-bearing:
//! `Vec::resize` -- which zero-fills, and which `lz4_flex`'s
`FrameDecoder` uses to grow its
//! destination buffer to the frame's *declared* maximum block size --
grows through `realloc`,
//! not `alloc`. A wrapper hooking only `alloc` would miss it entirely.
//! - Each row does one throwaway read before measuring, then resets the
counters, so lazy
//! one-time initialisation is not charged to the measured read.
//! - The counters cover the whole read, array construction included, so the
uncompressed row --
//! not zero -- is the floor to read each compressed row against.
use arrow_array::RecordBatch;
use arrow_array::builder::Int32Builder;
use arrow_ipc::CompressionType;
use arrow_ipc::reader::StreamReader;
use arrow_ipc::writer::{IpcWriteOptions, StreamWriter};
use arrow_schema::{DataType, Field, Schema};
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
static COUNT: AtomicUsize = AtomicUsize::new(0);
static BYTES: AtomicUsize = AtomicUsize::new(0);
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
struct Counting;
// SAFETY: every method forwards to `System` with the layout it was given,
and the counters are
// plain atomics that allocate nothing themselves, so no method can re-enter
the allocator.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
COUNT.fetch_add(1, Relaxed);
BYTES.fetch_add(layout.size(), Relaxed);
let live = LIVE.fetch_add(layout.size(), Relaxed) + layout.size();
PEAK.fetch_max(live, Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize)
-> *mut u8 {
COUNT.fetch_add(1, Relaxed);
if let Some(growth) = new_size.checked_sub(layout.size()) {
BYTES.fetch_add(growth, Relaxed);
let live = LIVE.fetch_add(growth, Relaxed) + growth;
PEAK.fetch_max(live, Relaxed);
} else {
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
}
unsafe { System.realloc(ptr, layout, new_size) }
}
}
// `alloc_zeroed` is deliberately not overridden: its default implementation
calls `self.alloc`,
// so those allocations are counted by the method above.
#[global_allocator]
static ALLOCATOR: Counting = Counting;
const BATCHES: usize = 10;
/// A batch of `cols` nullable Int32 columns of `rows` rows, so a message
carries many compressed
/// buffers -- one per field node, plus its validity -- rather than a few
large ones.
fn wide_batch(cols: usize, rows: usize) -> RecordBatch {
let schema = Arc::new(Schema::new(
(0..cols)
.map(|i| Field::new(format!("c{i}"), DataType::Int32, true))
.collect::<Vec<_>>(),
));
let columns = (0..cols)
.map(|col| {
let mut builder = Int32Builder::with_capacity(rows);
for row in 0..rows {
if row % 10 == 0 {
builder.append_null();
} else {
builder.append_value((row * (col + 1)) as i32);
}
}
Arc::new(builder.finish()) as _
})
.collect::<Vec<_>>();
RecordBatch::try_new(schema, columns).unwrap()
}
fn stream(batch: &RecordBatch, compression: Option<CompressionType>) ->
Vec<u8> {
let mut options = IpcWriteOptions::default();
if let Some(compression) = compression {
options = options
.try_with_compression(Some(compression))
.unwrap_or_else(|e| {
panic!("{compression:?} unavailable -- build with that
feature: {e}")
});
}
let mut buffer = Vec::new();
let mut writer =
StreamWriter::try_new_with_options(&mut buffer,
batch.schema().as_ref(), options).unwrap();
for _ in 0..BATCHES {
writer.write(batch).unwrap();
}
writer.finish().unwrap();
buffer
}
fn read_all(bytes: &[u8]) -> usize {
let reader = StreamReader::try_new(bytes, None).unwrap();
reader.map(|b| b.unwrap().num_rows()).sum()
}
fn measure(shape: &str, codec: &str, bytes: &[u8]) {
// Flush any lazy one-time allocation out of the way before the counters
are reset.
std::hint::black_box(read_all(bytes));
COUNT.store(0, Relaxed);
BYTES.store(0, Relaxed);
let base = LIVE.load(Relaxed);
PEAK.store(base, Relaxed);
let rows = read_all(bytes);
let mib = |n: usize| n as f64 / (1024.0 * 1024.0);
println!(
"{shape:<12} {codec:<6} {:>9} {:>14.2} MiB {:>10.2} MiB {:>10.2} MiB
{rows} rows in {BATCHES} batches",
COUNT.load(Relaxed),
mib(BYTES.load(Relaxed)),
mib(PEAK.load(Relaxed).saturating_sub(base)),
mib(bytes.len()),
);
}
fn main() {
println!(
"{:<12} {:<6} {:>9} {:>18} {:>14} {:>14}",
"shape", "codec", "allocs", "bytes allocated", "peak live", "stream
size"
);
// 4x8192 is the shape `benches/ipc_reader.rs` has always used. 200x4096
keeps every buffer
// small. 20x131072 puts each values buffer over 256 KiB, which is where
`lz4_flex`'s encoder
// stops declaring 64 KiB blocks and declares 4 MiB ones instead.
for (shape, cols, rows) in [
("4x8192", 4, 8192),
("200x4096", 200, 4096),
("20x131072", 20, 131072),
] {
let batch = wide_batch(cols, rows);
for (codec, compression) in [
("none", None),
("lz4", Some(CompressionType::LZ4_FRAME)),
("zstd", Some(CompressionType::ZSTD)),
] {
let bytes = stream(&batch, compression);
measure(shape, codec, &bytes);
}
println!();
}
}
```
--
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]