use std::{ collections::HashMap, sync::{LazyLock, Mutex}, thread::{self, ThreadId}, time::{Duration, Instant}, }; use cpu_time::ThreadTime; use super::Threads; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Group { Gui, Camera, Encode, Decode, } type Spent = [Duration; 4]; static SPENT: LazyLock>> = LazyLock::new(Default::default); pub fn tick(group: Group) { let Ok(time) = ThreadTime::try_now() else { return; }; if let Ok(mut spent) = SPENT.lock() { spent.insert(thread::current().id(), (group, time.as_duration())); } } fn spent() -> Option { let spent = SPENT.lock().ok()?; let mut total = Spent::default(); for (group, time) in spent.values() { total[*group as usize] += *time; } Some(total) } #[derive(Default)] pub struct Sampler { previous: Option<(Instant, Spent)>, } impl Sampler { pub fn sample(&mut self, cores: f32) -> Option { let now = (Instant::now(), spent()?); let (at, then) = self.previous.replace(now)?; let seconds = now.0.duration_since(at).as_secs_f32().max(f32::EPSILON) * cores; let cpu = |group: Group| { let index = group as usize; now.1[index].saturating_sub(then[index]).as_secs_f32() * 100. / seconds }; Some(Threads { gui: cpu(Group::Gui), camera: cpu(Group::Camera), encode: cpu(Group::Encode), decode: cpu(Group::Decode), }) } }