flybrain/services/flysim/crates/fly-session/src/profile.rs
acamilo fa8c9305a7 PERF-01: spikes gathered per tick, 1 Hz session snapshots, fewer copies
- flybrain-core: LifNetwork::tick_spikes, the last CPU tick's spike list
  (None under the GPU backend); a test proves it is exactly the neurons the
  tick stamped and that window unions equal the last_spike_ms scan.
- legacy agent: Prepare runs its ticks one at a time and ORs each tick's list
  into the transition's bitset; Commit uses it instead of scanning 139,255
  last-spike times (falls back to the scan when no list is kept).
- legacy composition: a service session publishes its committed snapshot
  every 60th boundary (plus every boundary with events or boundary actions);
  nothing in the release subscribes, and each publication seals copies of
  the frame and the audio.
- coordinator: a single dispatch job is called in place; worker shell moves
  the reply result instead of cloning it; publication promotions begin when
  Advance answers whatever the cadence.
- profile: record() for a sample from another clock; finer spans (shell,
  local lane, handlers, advance parse/build, the brain's phase clock).
2026-09-30 02:15:25 +00:00

96 lines
3.1 KiB
Rust

//! A switchable per-phase timer for measuring the session runtime (TASK-01 review N5).
//!
//! Off unless `FLY_SESSION_PROFILE` is set when the process starts; off, a span is one relaxed
//! atomic load. On, every span adds its duration to a process-wide table that [`report`] reads.
//! In-process execution puts the coordinator and every worker in one table; a worker process
//! keeps its own. Not a service metric: a measurement tool.
use std::collections::BTreeMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::{Duration, Instant};
static STATE: AtomicU8 = AtomicU8::new(0); // 0 unknown, 1 off, 2 on
static TABLE: Mutex<BTreeMap<&'static str, (u64, Duration, Duration)>> = Mutex::new(BTreeMap::new());
/// Whether profiling is on for this process (`FLY_SESSION_PROFILE`).
pub fn enabled() -> bool {
on()
}
fn on() -> bool {
match STATE.load(Ordering::Relaxed) {
1 => false,
2 => true,
_ => {
let enabled = std::env::var_os("FLY_SESSION_PROFILE").is_some();
STATE.store(if enabled { 2 } else { 1 }, Ordering::Relaxed);
enabled
}
}
}
/// Times until dropped.
pub struct Span(Option<(&'static str, Instant)>);
/// Starts timing `name`.
pub fn span(name: &'static str) -> Span {
Span(on().then(|| (name, Instant::now())))
}
impl Drop for Span {
fn drop(&mut self) {
if let Some((name, started)) = self.0.take() {
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO));
let elapsed = started.elapsed();
entry.0 += 1;
entry.1 += elapsed;
entry.2 = entry.2.max(elapsed);
}
}
}
/// Adds one sample measured elsewhere (a clock the caller already runs) under `name`.
pub fn record(name: &'static str, elapsed: Duration) {
if !on() {
return;
}
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = table.entry(name).or_insert((0, Duration::ZERO, Duration::ZERO));
entry.0 += 1;
entry.1 += elapsed;
entry.2 = entry.2.max(elapsed);
}
/// `(name, count, mean)` for every span recorded, then clears the table.
pub fn report() -> Vec<(&'static str, u64, Duration)> {
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let out = table
.iter()
.map(|(name, (count, total, _))| (*name, *count, *total / (*count).max(1) as u32))
.collect();
table.clear();
out
}
/// As [`report`], with each span's longest single sample: `(name, count, mean, max)`.
pub fn report_with_max() -> Vec<(&'static str, u64, Duration, Duration)> {
let mut table = TABLE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let out = table
.iter()
.map(|(name, (count, total, max))| {
(*name, *count, *total / (*count).max(1) as u32, *max)
})
.collect();
table.clear();
out
}