use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
thread_local! {
static ALLOCATIONS: Cell<usize> = const { Cell::new(0) };
static LIVE: Cell<isize> = const { Cell::new(0) };
static PEAK: Cell<isize> = const { Cell::new(0) };
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stats {
pub allocations: usize,
pub peak_bytes: usize,
pub net_bytes: isize,
}
pub struct CountingAlloc;
fn record(delta: isize, counts_as_allocation: bool) {
let _ = ALLOCATIONS.try_with(|a| {
if counts_as_allocation {
a.set(a.get() + 1);
}
});
let _ = LIVE.try_with(|live| {
let now = live.get() + delta;
live.set(now);
let _ = PEAK.try_with(|peak| {
if now > peak.get() {
peak.set(now);
}
});
});
}
unsafe impl GlobalAlloc for CountingAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { System.alloc(layout) };
if !ptr.is_null() {
record(layout.size() as isize, true);
}
ptr
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let ptr = unsafe { System.alloc_zeroed(layout) };
if !ptr.is_null() {
record(layout.size() as isize, true);
}
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) };
record(-(layout.size() as isize), false);
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let new_ptr = unsafe { System.realloc(ptr, layout, new_size) };
if !new_ptr.is_null() {
record(new_size as isize - layout.size() as isize, true);
}
new_ptr
}
}
pub fn measure<R>(f: impl FnOnce() -> R) -> (R, Stats) {
ALLOCATIONS.with(|a| a.set(0));
LIVE.with(|l| l.set(0));
PEAK.with(|p| p.set(0));
let result = f();
let stats = Stats {
allocations: ALLOCATIONS.with(Cell::get),
peak_bytes: PEAK.with(Cell::get).max(0) as usize,
net_bytes: LIVE.with(Cell::get),
};
(result, stats)
}