From 60dc3a76f7d8c34244d1066353af9a761e87c9bd Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 8 Nov 2026 13:33:38 +0100 Subject: [PATCH] feat: log slow camera and detection operations --- src/diagnostics.rs | 83 ++++++++++++++++++++++++++++++++++++++++++++++ src/hand_pose.rs | 16 +++++++-- src/main.rs | 40 ++++++++++++++++++---- src/palm.rs | 14 ++++++-- 4 files changed, 140 insertions(+), 13 deletions(-) create mode 100644 src/diagnostics.rs diff --git a/src/diagnostics.rs b/src/diagnostics.rs new file mode 100644 index 0000000..e3cc293 --- /dev/null +++ b/src/diagnostics.rs @@ -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, + 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(&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)); + } +} diff --git a/src/hand_pose.rs b/src/hand_pose.rs index 51dc05f..97c0d7f 100644 --- a/src/hand_pose.rs +++ b/src/hand_pose.rs @@ -7,6 +7,7 @@ use opencv::{ pub struct HandPose { net: dnn::Net, + inference_log: crate::diagnostics::SlowLog, } impl HandPose { @@ -17,7 +18,14 @@ impl HandPose { let mut net = dnn::read_net_from_onnx_buffer(&bytes)?; net.set_preferable_backend(dnn::DNN_BACKEND_OPENCV)?; net.set_preferable_target(dnn::DNN_TARGET_CPU)?; - Ok(Self { net }) + Ok(Self { + net, + inference_log: crate::diagnostics::SlowLog::new( + "hand landmark model inference", + std::time::Duration::from_millis(100), + "Second-stage open-hand verification runs on CPU.", + ), + }) } pub fn is_open(&mut self, frame: &Mat, palm: &[[f32; 2]; 7]) -> opencv::Result { @@ -76,8 +84,10 @@ impl HandPose { let input = normalized.reshape_nd(1, &[1, 224, 224, 3])?; self.net.set_input_def(&input)?; let mut outputs: Vector = Vector::new(); - self.net - .forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?)?; + self.inference_log.run(|| { + self.net + .forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?) + })?; if outputs.len() != 4 { return Err(opencv::Error::new( core::StsError, diff --git a/src/main.rs b/src/main.rs index 93f7d1e..1ba6db6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ use slint::{Rgb8Pixel, SharedPixelBuffer}; slint::include_modules!(); mod capture; +mod diagnostics; mod hand_pose; mod palm; @@ -43,8 +44,13 @@ fn main() -> Result<(), Box> { } } + let mut camera_log = diagnostics::SlowLog::new( + "camera read", + Duration::from_millis(100), + "Check camera passthrough and camera frame rate.", + ); for _ in 0..30 { - if !cam.read(&mut frame)? || frame.empty() { + if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() { return Err("Failed to capture a frame".into()); } } @@ -70,26 +76,44 @@ fn main() -> Result<(), Box> { // A rendezvous channel drops samples while inference is busy, avoiding a backlog. let (detection_tx, detection_rx) = mpsc::sync_channel::(0); let detection_worker = thread::spawn(move || { + let mut inference_log = diagnostics::SlowLog::new( + "palm + open-hand detection", + palm::DETECTION_INTERVAL, + "Detection exceeds the 250 ms sampling budget; check model-stage warnings.", + ); + let mut gap_log = diagnostics::SlowLog::new( + "detection result interval", + palm::STALE_AFTER, + "Results are at least 750 ms apart: the tracker expires and the steadiness timer restarts.", + ); + let mut last_result: Option = None; while let Ok(sample) = detection_rx.recv() { - let result = match detector.detect(&sample) { + let result = match inference_log.run(|| detector.detect(&sample)) { Ok(palm) => palm, Err(error) => { eprintln!("Palm detection error: {error}"); None } }; - detection_tracker - .lock() - .unwrap() - .update(result, Instant::now()); + let now = Instant::now(); + if let Some(previous) = last_result { + gap_log.record(now.duration_since(previous)); + } + last_result = Some(now); + detection_tracker.lock().unwrap().update(result, now); } }); let worker = thread::spawn(move || -> opencv::Result<()> { + let mut processing_log = diagnostics::SlowLog::new( + "preview processing", + Duration::from_millis(100), + "Includes tracker lock, circle drawing and RGB conversion; excludes camera read.", + ); let mut sequence = capture::Sequence::default(); let mut last_detection = Instant::now() - palm::DETECTION_INTERVAL; while worker_running.load(Ordering::Relaxed) { - if !cam.read(&mut frame)? || frame.empty() { + if !camera_log.run(|| cam.read(&mut frame))? || frame.empty() { eprintln!("Camera stopped providing frames"); break; } @@ -114,6 +138,8 @@ fn main() -> Result<(), Box> { presentation: sequence.presentation(now), }; + processing_log.record(now.elapsed()); + // Publish image and presentation together so a countdown frame never // accidentally contains the palm circle from an older capture frame. *worker_frame.lock().unwrap() = Some(preview); diff --git a/src/palm.rs b/src/palm.rs index 521ffa1..fb3cc90 100644 --- a/src/palm.rs +++ b/src/palm.rs @@ -7,7 +7,7 @@ use opencv::{ }; pub const DETECTION_INTERVAL: Duration = Duration::from_millis(250); -const STALE_AFTER: Duration = Duration::from_millis(750); +pub const STALE_AFTER: Duration = Duration::from_millis(750); #[derive(Clone, Copy, Debug)] pub struct Palm { @@ -18,6 +18,7 @@ pub struct Palm { pub struct Detector { net: dnn::Net, + inference_log: crate::diagnostics::SlowLog, hand_pose: crate::hand_pose::HandPose, anchors: Vec<(f32, f32)>, } @@ -46,6 +47,11 @@ impl Detector { } Ok(Self { net, + inference_log: crate::diagnostics::SlowLog::new( + "palm model inference", + Duration::from_millis(100), + "OpenCV DNN runs on CPU; check VM CPU allocation and load.", + ), anchors, hand_pose: crate::hand_pose::HandPose::new()?, }) @@ -85,8 +91,10 @@ impl Detector { let input = normalized.reshape_nd(1, &[1, 192, 192, 3])?; self.net.set_input_def(&input)?; let mut outputs: Vector = Vector::new(); - self.net - .forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?)?; + self.inference_log.run(|| { + self.net + .forward(&mut outputs, &self.net.get_unconnected_out_layers_names()?) + })?; let boxes = outputs.get(0)?; let scores = outputs.get(1)?; let boxes = boxes.data_typed::()?;