feat: log slow camera and detection operations

This commit is contained in:
2026-11-08 13:33:38 +01:00
parent 93bb1e3b22
commit 60dc3a76f7
4 changed files with 140 additions and 13 deletions

83
src/diagnostics.rs Normal file
View File

@@ -0,0 +1,83 @@
//! Low-overhead, rate-limited timing warnings written to stderr.
use std::time::{Duration, Instant};
const LOG_INTERVAL: Duration = Duration::from_secs(5);
pub struct SlowLog {
operation: &'static str,
threshold: Duration,
hint: &'static str,
last_warning: Option<Instant>,
suppressed: u64,
worst: Duration,
}
impl SlowLog {
pub fn new(operation: &'static str, threshold: Duration, hint: &'static str) -> Self {
Self {
operation,
threshold,
hint,
last_warning: None,
suppressed: 0,
worst: Duration::ZERO,
}
}
pub fn run<T>(&mut self, operation: impl FnOnce() -> T) -> T {
let start = Instant::now();
let result = operation();
self.record(start.elapsed());
result
}
pub fn record(&mut self, elapsed: Duration) {
let now = Instant::now();
if self.should_warn(elapsed, now) {
eprintln!(
"[performance WARN] {}: {} ms (threshold {} ms; worst {} ms; {} additional slow samples since previous warning). {}",
self.operation,
elapsed.as_millis(),
self.threshold.as_millis(),
self.worst.as_millis(),
self.suppressed,
self.hint,
);
self.suppressed = 0;
self.worst = Duration::ZERO;
}
}
fn should_warn(&mut self, elapsed: Duration, now: Instant) -> bool {
if elapsed < self.threshold {
return false;
}
self.worst = self.worst.max(elapsed);
if self
.last_warning
.is_none_or(|last| now.duration_since(last) >= LOG_INTERVAL)
{
self.last_warning = Some(now);
true
} else {
self.suppressed += 1;
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warns_immediately_then_rate_limits_and_preserves_worst_duration() {
let mut log = SlowLog::new("test", Duration::from_millis(250), "");
let now = Instant::now();
assert!(!log.should_warn(Duration::from_millis(249), now));
assert!(log.should_warn(Duration::from_millis(250), now));
assert!(!log.should_warn(Duration::from_millis(900), now + Duration::from_secs(1)));
assert_eq!(log.suppressed, 1);
assert!(log.should_warn(Duration::from_millis(300), now + LOG_INTERVAL));
assert_eq!(log.worst, Duration::from_millis(900));
}
}