TASK-01 review N5: the per-boundary costs measured, the world's seals concurrent, bounded history
- fly-session::profile: switchable per-phase spans (FLY_SESSION_PROFILE), in the coordinator's phases, the world's advance and the agent's prepare and commit. - The world seals the view, the image and the audio chunk concurrently. - Coordinator::bound_history: a service session keeps the newest 4096 transitions of trace, phase and audit logs and latency samples (it grew without bound). - tests/speed.rs: legacy loop against the session on one box, unpaced and paced at 1x, in-process and process, with the span breakdown.
This commit is contained in:
parent
7a61877e78
commit
46d07260e9
8 changed files with 163 additions and 10 deletions
|
|
@ -38,6 +38,9 @@ fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
|
||||||
g
|
g
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
|
||||||
|
const HISTORY: usize = 4096;
|
||||||
|
|
||||||
const COORDINATOR_CLIENT: &str = "coordinator";
|
const COORDINATOR_CLIENT: &str = "coordinator";
|
||||||
const ENV_CLIENT: &str = "legacy-world";
|
const ENV_CLIENT: &str = "legacy-world";
|
||||||
const ENV_SERVICE: &str = "env.world";
|
const ENV_SERVICE: &str = "env.world";
|
||||||
|
|
@ -407,6 +410,9 @@ impl LegacySession {
|
||||||
// itself; a parity run is a measurement.
|
// itself; a parity run is a measurement.
|
||||||
if config.record {
|
if config.record {
|
||||||
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
|
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
|
||||||
|
} else {
|
||||||
|
// A service session runs indefinitely: its in-memory history stays bounded.
|
||||||
|
coordinator.bound_history(HISTORY);
|
||||||
}
|
}
|
||||||
Ok(LegacySession {
|
Ok(LegacySession {
|
||||||
coordinator,
|
coordinator,
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ use flybrain_core::agent::{AgentConfig, NeuralAgent};
|
||||||
use flybrain_core::dataset::load_brain_dataset_from_dir;
|
use flybrain_core::dataset::load_brain_dataset_from_dir;
|
||||||
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
|
||||||
use flybrain_core::lif::SweepPlan;
|
use flybrain_core::lif::SweepPlan;
|
||||||
|
use flybrain_gb::GameAdapter;
|
||||||
use flybrain_gb::pokemon_red::PokemonRedReward;
|
use flybrain_gb::pokemon_red::PokemonRedReward;
|
||||||
use flybrain_gb::ratchet::Ratchet;
|
use flybrain_gb::ratchet::Ratchet;
|
||||||
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
|
||||||
|
|
@ -145,6 +146,7 @@ async fn session_against_legacy_per_frame() {
|
||||||
session.step().await.unwrap();
|
session.step().await.unwrap();
|
||||||
}
|
}
|
||||||
session.coordinator.metrics.clear();
|
session.coordinator.metrics.clear();
|
||||||
|
let _ = fly_session::profile::report();
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
for _ in 0..frames {
|
for _ in 0..frames {
|
||||||
session.step().await.unwrap();
|
session.step().await.unwrap();
|
||||||
|
|
@ -159,6 +161,12 @@ async fn session_against_legacy_per_frame() {
|
||||||
per / legacy_per
|
per / legacy_per
|
||||||
);
|
);
|
||||||
if !paced {
|
if !paced {
|
||||||
|
for (name, count, mean) in fly_session::profile::report() {
|
||||||
|
eprintln!(
|
||||||
|
" span {name:<22} mean {:>8.0} us n {count}",
|
||||||
|
mean.as_secs_f64() * 1e6
|
||||||
|
);
|
||||||
|
}
|
||||||
for name in session.coordinator.metrics.names() {
|
for name in session.coordinator.metrics.names() {
|
||||||
let p = session.coordinator.metrics.percentiles(&name).unwrap();
|
let p = session.coordinator.metrics.percentiles(&name).unwrap();
|
||||||
eprintln!(
|
eprintln!(
|
||||||
|
|
|
||||||
|
|
@ -379,6 +379,8 @@ pub struct Coordinator {
|
||||||
/// Leave a requested rollback for the host to apply (`apply_pending_rollback`).
|
/// Leave a requested rollback for the host to apply (`apply_pending_rollback`).
|
||||||
defer_rollbacks: bool,
|
defer_rollbacks: bool,
|
||||||
pending_rollback: Option<(u64, EpisodeRequest)>,
|
pending_rollback: Option<(u64, EpisodeRequest)>,
|
||||||
|
/// [`Coordinator::bound_history`].
|
||||||
|
history_limit: Option<usize>,
|
||||||
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
|
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
|
||||||
stats: Stats,
|
stats: Stats,
|
||||||
/// The ordered actions this session took, for the ordering assertions.
|
/// The ordered actions this session took, for the ordering assertions.
|
||||||
|
|
@ -498,6 +500,7 @@ impl Coordinator {
|
||||||
state_format_id: None,
|
state_format_id: None,
|
||||||
defer_rollbacks: false,
|
defer_rollbacks: false,
|
||||||
pending_rollback: None,
|
pending_rollback: None,
|
||||||
|
history_limit: None,
|
||||||
lifecycle_acks: Vec::new(),
|
lifecycle_acks: Vec::new(),
|
||||||
stats: Stats::default(),
|
stats: Stats::default(),
|
||||||
audit: Vec::new(),
|
audit: Vec::new(),
|
||||||
|
|
@ -630,6 +633,27 @@ impl Coordinator {
|
||||||
self.state_format_id = Some(id(state_format_id));
|
self.state_format_id = Some(id(state_format_id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bounds the session's in-memory history -- the behaviour trace, the phase log, the audit
|
||||||
|
/// log and the latency samples -- to the newest `keep` entries each, for a session that runs
|
||||||
|
/// indefinitely (the live fly). Unbounded by default: a test reads all of it.
|
||||||
|
pub fn bound_history(&mut self, keep: usize) {
|
||||||
|
self.history_limit = Some(keep);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim_history(&mut self) {
|
||||||
|
let Some(keep) = self.history_limit else { return };
|
||||||
|
fn trim<T>(items: &mut Vec<T>, keep: usize) {
|
||||||
|
if items.len() > 2 * keep {
|
||||||
|
items.drain(..items.len() - keep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trim(&mut self.trace.transitions, keep);
|
||||||
|
trim(&mut self.trace.phases, keep);
|
||||||
|
trim(&mut self.audit, keep);
|
||||||
|
trim(&mut self.injection_log, keep);
|
||||||
|
self.metrics.truncate(keep);
|
||||||
|
}
|
||||||
|
|
||||||
/// Leave a rollback the task asks for pending at its boundary, for the host to apply with
|
/// Leave a rollback the task asks for pending at its boundary, for the host to apply with
|
||||||
/// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts
|
/// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts
|
||||||
/// while one is pending.
|
/// while one is pending.
|
||||||
|
|
@ -2200,13 +2224,20 @@ impl Coordinator {
|
||||||
|
|
||||||
// ---- Phase A: prepare all agents concurrently
|
// ---- Phase A: prepare all agents concurrently
|
||||||
self.transition(Phase::Preparing(k))?;
|
self.transition(Phase::Preparing(k))?;
|
||||||
|
let span = crate::profile::span("coord.prepare");
|
||||||
let prepared = self.prepare_all(k, descriptor.step_duration).await?;
|
let prepared = self.prepare_all(k, descriptor.step_duration).await?;
|
||||||
|
drop(span);
|
||||||
|
|
||||||
// ---- Phase B: build and apply one complete batch
|
// ---- Phase B: build and apply one complete batch
|
||||||
self.transition(Phase::Applying(k))?;
|
self.transition(Phase::Applying(k))?;
|
||||||
|
let span = crate::profile::span("coord.executor");
|
||||||
let controls = self.build_batch(k, &descriptor, &old_observation)?;
|
let controls = self.build_batch(k, &descriptor, &old_observation)?;
|
||||||
|
drop(span);
|
||||||
let batch_id = self.batch_id(k);
|
let batch_id = self.batch_id(k);
|
||||||
|
let span = crate::profile::span("coord.advance");
|
||||||
let step_result = self.advance(k, &batch_id, &controls).await?;
|
let step_result = self.advance(k, &batch_id, &controls).await?;
|
||||||
|
drop(span);
|
||||||
|
let span = crate::profile::span("coord.observe");
|
||||||
|
|
||||||
// ---- Phase C: observe and evaluate the task once
|
// ---- Phase C: observe and evaluate the task once
|
||||||
self.transition(Phase::Observing(k + 1))?;
|
self.transition(Phase::Observing(k + 1))?;
|
||||||
|
|
@ -2221,6 +2252,8 @@ impl Coordinator {
|
||||||
.current_inspection
|
.current_inspection
|
||||||
.clone()
|
.clone()
|
||||||
.expect("a bootstrapped session holds O[k]'s inspection");
|
.expect("a bootstrapped session holds O[k]'s inspection");
|
||||||
|
drop(span);
|
||||||
|
let span = crate::profile::span("coord.evaluate");
|
||||||
let evaluation = self
|
let evaluation = self
|
||||||
.task
|
.task
|
||||||
.evaluate_transition(&scope, &old_inspection, &new_inspection, &controls)
|
.evaluate_transition(&scope, &old_inspection, &new_inspection, &controls)
|
||||||
|
|
@ -2260,8 +2293,10 @@ impl Coordinator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
drop(span);
|
||||||
// ---- Phase D: commit all agent outcomes concurrently
|
// ---- Phase D: commit all agent outcomes concurrently
|
||||||
self.transition(Phase::Committing(k))?;
|
self.transition(Phase::Committing(k))?;
|
||||||
|
let commit_span = crate::profile::span("coord.commit");
|
||||||
let new_views: BTreeMap<String, flybus::Artifact> = step_result
|
let new_views: BTreeMap<String, flybus::Artifact> = step_result
|
||||||
.observation
|
.observation
|
||||||
.sensory_views
|
.sensory_views
|
||||||
|
|
@ -2284,6 +2319,8 @@ impl Coordinator {
|
||||||
.commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views)
|
.commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
drop(commit_span);
|
||||||
|
let span = crate::profile::span("coord.boundary");
|
||||||
// Only once every commit succeeded does the committed boundary move.
|
// Only once every commit succeeded does the committed boundary move.
|
||||||
self.transition(Phase::Ready(k + 1))?;
|
self.transition(Phase::Ready(k + 1))?;
|
||||||
for index in 0..self.agents.len() {
|
for index in 0..self.agents.len() {
|
||||||
|
|
@ -2362,6 +2399,8 @@ impl Coordinator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
drop(span);
|
||||||
|
let span = crate::profile::span("coord.trace_publish");
|
||||||
let event_ids: Vec<Id> = evaluation.events.iter().map(|e| e.id.clone()).collect();
|
let event_ids: Vec<Id> = evaluation.events.iter().map(|e| e.id.clone()).collect();
|
||||||
let decisions: BTreeMap<Id, TypedValue> = prepared
|
let decisions: BTreeMap<Id, TypedValue> = prepared
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -2419,8 +2458,10 @@ impl Coordinator {
|
||||||
self.pause.store(false, std::sync::atomic::Ordering::SeqCst);
|
self.pause.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||||
self.audit.push(format!("pause:{}", k + 1));
|
self.audit.push(format!("pause:{}", k + 1));
|
||||||
}
|
}
|
||||||
|
drop(span);
|
||||||
// The critical path: one whole transition, pacing sleep included.
|
// The critical path: one whole transition, pacing sleep included.
|
||||||
self.metrics.record("step", step_started.elapsed());
|
self.metrics.record("step", step_started.elapsed());
|
||||||
|
self.trim_history();
|
||||||
Ok(StepReport { boundary: k + 1, paused, terminal })
|
Ok(StepReport { boundary: k + 1, paused, terminal })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1005,7 +1005,9 @@ impl LegacyAgentWorker {
|
||||||
let brain_ticks = accumulator.brain_ticks();
|
let brain_ticks = accumulator.brain_ticks();
|
||||||
let remainder = accumulator.remainder();
|
let remainder = accumulator.remainder();
|
||||||
self.transition_start_ms = agent.network.ms;
|
self.transition_start_ms = agent.network.ms;
|
||||||
|
let ticks_span = crate::profile::span("agent.ticks");
|
||||||
agent.network.step(ticks);
|
agent.network.step(ticks);
|
||||||
|
drop(ticks_span);
|
||||||
if agent.network.ms != brain_ticks as f64 {
|
if agent.network.ms != brain_ticks as f64 {
|
||||||
return Err(applied(
|
return Err(applied(
|
||||||
ErrorCode::Internal,
|
ErrorCode::Internal,
|
||||||
|
|
@ -1110,7 +1112,9 @@ impl LegacyAgentWorker {
|
||||||
}
|
}
|
||||||
let context = self.read_context(¶ms.next_decision_context)?;
|
let context = self.read_context(¶ms.next_decision_context)?;
|
||||||
// The complete request and its owned artifact are validated before anything applies.
|
// The complete request and its owned artifact are validated before anything applies.
|
||||||
|
let read_span = crate::profile::span("agent.read_lcd");
|
||||||
let frame = self.read_lcd(ctx, ¶ms.next_input).await?;
|
let frame = self.read_lcd(ctx, ¶ms.next_input).await?;
|
||||||
|
drop(read_span);
|
||||||
|
|
||||||
self.status.set_state(WorkerState::Committing);
|
self.status.set_state(WorkerState::Committing);
|
||||||
let agent = self.agent.as_mut().expect("initialized");
|
let agent = self.agent.as_mut().expect("initialized");
|
||||||
|
|
@ -1139,7 +1143,9 @@ impl LegacyAgentWorker {
|
||||||
self.transient.location = Some(location);
|
self.transient.location = Some(location);
|
||||||
self.transient.blocked_since_ms = ms;
|
self.transient.blocked_since_ms = ms;
|
||||||
}
|
}
|
||||||
|
let spikes_span = crate::profile::span("agent.spikes");
|
||||||
let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms);
|
let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms);
|
||||||
|
drop(spikes_span);
|
||||||
// 4. Retain the next context and acknowledge k+1.
|
// 4. Retain the next context and acknowledge k+1.
|
||||||
let digest = context.digest.clone();
|
let digest = context.digest.clone();
|
||||||
self.context = Some(context);
|
self.context = Some(context);
|
||||||
|
|
@ -1152,6 +1158,7 @@ impl LegacyAgentWorker {
|
||||||
decision_context_digest: digest,
|
decision_context_digest: digest,
|
||||||
telemetry: self.telemetry(),
|
telemetry: self.telemetry(),
|
||||||
};
|
};
|
||||||
|
let _seal_span = crate::profile::span("agent.seal_spikes");
|
||||||
let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
|
let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| applied(e.code, e.message))?;
|
.map_err(|e| applied(e.code, e.message))?;
|
||||||
|
|
|
||||||
|
|
@ -857,10 +857,33 @@ impl LegacyGameboyEnvironment {
|
||||||
client: &flybus::Client,
|
client: &flybus::Client,
|
||||||
audio: Option<Vec<u8>>,
|
audio: Option<Vec<u8>>,
|
||||||
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
|
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
|
||||||
let frame =
|
let image = {
|
||||||
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?;
|
let _span = crate::profile::span("env.image");
|
||||||
let image = memory_image(&mut live.emulator).map_err(backend_failure)?;
|
memory_image(&mut live.emulator).map_err(backend_failure)?
|
||||||
let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?;
|
};
|
||||||
|
if let Some(raw) = &audio
|
||||||
|
&& raw.len() % AUDIO_CHANNELS as usize != 0
|
||||||
|
{
|
||||||
|
return Err(backend_failure("binjgb returned half a stereo frame"));
|
||||||
|
}
|
||||||
|
let audio_f32 = audio.as_deref().map(audio_f32le);
|
||||||
|
// The three artifacts are independent: they are sealed concurrently, so the boundary
|
||||||
|
// waits for the router's round trips once rather than three times.
|
||||||
|
let seal_span = crate::profile::span("env.seal");
|
||||||
|
let (frame, memory, samples) = tokio::join!(
|
||||||
|
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer),
|
||||||
|
media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image),
|
||||||
|
async {
|
||||||
|
match &audio_f32 {
|
||||||
|
Some(bytes) => media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), bytes)
|
||||||
|
.await
|
||||||
|
.map(Some),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
drop(seal_span);
|
||||||
|
let (frame, memory, samples) = (frame?, memory?, samples?);
|
||||||
let view = ViewRef {
|
let view = ViewRef {
|
||||||
view_id: gameboy::VIEW_ID.to_owned(),
|
view_id: gameboy::VIEW_ID.to_owned(),
|
||||||
produced_step: live.boundary,
|
produced_step: live.boundary,
|
||||||
|
|
@ -876,13 +899,8 @@ impl LegacyGameboyEnvironment {
|
||||||
(MEMORY_ATTACHMENT.to_owned(), memory),
|
(MEMORY_ATTACHMENT.to_owned(), memory),
|
||||||
];
|
];
|
||||||
let mut chunks = Vec::new();
|
let mut chunks = Vec::new();
|
||||||
if let Some(raw) = audio {
|
if let (Some(raw), Some(samples)) = (audio, samples) {
|
||||||
if raw.len() % AUDIO_CHANNELS as usize != 0 {
|
|
||||||
return Err(backend_failure("binjgb returned half a stereo frame"));
|
|
||||||
}
|
|
||||||
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64;
|
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64;
|
||||||
let samples =
|
|
||||||
media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?;
|
|
||||||
chunks.push(AudioRef {
|
chunks.push(AudioRef {
|
||||||
stream_id: id(AUDIO_STREAM_ID),
|
stream_id: id(AUDIO_STREAM_ID),
|
||||||
first_sample: live.audio_next_sample,
|
first_sample: live.audio_next_sample,
|
||||||
|
|
@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment {
|
||||||
let applied_from = live.boundary;
|
let applied_from = live.boundary;
|
||||||
|
|
||||||
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio.
|
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio.
|
||||||
|
let frame_span = crate::profile::span("env.frame");
|
||||||
live.buttons = mask;
|
live.buttons = mask;
|
||||||
live.emulator.set_buttons(mask);
|
live.emulator.set_buttons(mask);
|
||||||
live.emulator
|
live.emulator
|
||||||
|
|
@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment {
|
||||||
live.framebuffer
|
live.framebuffer
|
||||||
.copy_from_slice(live.emulator.framebuffer());
|
.copy_from_slice(live.emulator.framebuffer());
|
||||||
let audio = live.emulator.take_audio_u8();
|
let audio = live.emulator.take_audio_u8();
|
||||||
|
drop(frame_span);
|
||||||
live.boundary += 1;
|
live.boundary += 1;
|
||||||
live.world_time = live
|
live.world_time = live
|
||||||
.world_time
|
.world_time
|
||||||
|
|
|
||||||
|
|
@ -38,6 +38,7 @@ pub mod measure;
|
||||||
pub mod media;
|
pub mod media;
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
pub mod phase;
|
pub mod phase;
|
||||||
|
pub mod profile;
|
||||||
pub mod publish;
|
pub mod publish;
|
||||||
pub mod rpc;
|
pub mod rpc;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
|
|
||||||
|
|
@ -79,6 +79,16 @@ impl Metrics {
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
self.samples.clear();
|
self.samples.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bounds every path to between `keep` and `2 * keep` of its newest samples (trimmed in
|
||||||
|
/// batches, so a long run does not shift the vector every step).
|
||||||
|
pub fn truncate(&mut self, keep: usize) {
|
||||||
|
for values in self.samples.values_mut() {
|
||||||
|
if values.len() > 2 * keep {
|
||||||
|
values.drain(..values.len() - keep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This process's peak resident set, in KiB, from its own status file.
|
/// This process's peak resident set, in KiB, from its own status file.
|
||||||
|
|
|
||||||
60
services/flysim/crates/fly-session/src/profile.rs
Normal file
60
services/flysim/crates/fly-session/src/profile.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
//! 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)>> = Mutex::new(BTreeMap::new());
|
||||||
|
|
||||||
|
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));
|
||||||
|
entry.0 += 1;
|
||||||
|
entry.1 += started.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
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue