stackler 0.1.0

A lightweight, always-on stack telemetry library that requires no instrumentation.
Documentation
//! What a thread pool spends on stacks, and what it uses.
//!
//! Six workers recurse to six different depths. None of them reports anything
//! about itself except the odd [`stackler::sample`]; the peaks come out of the
//! stacks themselves, read from the main thread after the fact.
//!
//! ```sh
//! cargo run --release --example pool --features full
//! ```

use std::{
    hint::black_box,
    sync::{Arc, Barrier},
    thread,
    time::Duration,
};

/// The stack each worker reserves — the default for a `std` thread.
const STACK_SIZE: usize = 2 * 1024 * 1024;
const WORKERS: usize = 6;

/// Recurses `levels` deep, using a few kilobytes per level.
///
/// `#[inline(never)]` keeps every level in a frame of its own; an inlined
/// recursion reserves its stack up front, where a watermark cannot see it happen.
#[inline(never)]
fn work(levels: usize) {
    let mut frame = [0u8; 3 * 1024];
    black_box(&mut frame);

    // Not needed for the peaks below — this is what fills the depth histogram.
    stackler::sample();

    if levels > 0 {
        work(levels - 1);
    }
}

fn main() {
    stackler::Stackler::new().install();

    // Keeps every worker's watermark up to date without asking them anything.
    let _sampler = stackler::sampler::spawn(Duration::from_millis(100)).unwrap();

    let barrier = Arc::new(Barrier::new(WORKERS + 1));
    let hold = Arc::new(Barrier::new(WORKERS + 1));

    let workers: Vec<_> = (0..WORKERS)
        .map(|i| {
            let (barrier, hold) = (Arc::clone(&barrier), Arc::clone(&hold));

            thread::Builder::new()
                .stack_size(STACK_SIZE)
                .spawn(move || {
                    for _ in 0..(WORKERS - i) * 4 {
                        work(i * 3 + 1);
                    }

                    barrier.wait();
                    // Stay alive while the main thread looks at us.
                    hold.wait();
                })
                .unwrap()
        })
        .collect();

    barrier.wait();

    // Nothing above this line reported a peak; this is where they come from.
    stackler::poll_all();

    println!("{}", stackler::stats());
    stackler::for_each_thread(|thread| println!("{thread}"));

    let stats = stackler::stats();
    println!(
        "\n{:.1} MiB of stack reserved for {:.1} KiB of use — {:.2}% of it is doing nothing",
        stats.reserved_sum as f64 / (1024.0 * 1024.0),
        stats.peak_sum as f64 / 1024.0,
        100.0 - stats.utilization().unwrap_or(0.0) * 100.0,
    );

    hold.wait();
    for worker in workers {
        worker.join().unwrap();
    }
}