| 1 | use std::{ |
| 2 | collections::HashMap, |
| 3 | sync::{LazyLock, Mutex}, |
| 4 | thread::{self, ThreadId}, |
| 5 | time::{Duration, Instant}, |
| 6 | }; |
| 7 | |
| 8 | use cpu_time::ThreadTime; |
| 9 | |
| 10 | use super::Threads; |
| 11 | |
| 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 13 | pub enum Group { |
| 14 | Gui, |
| 15 | Camera, |
| 16 | Encode, |
| 17 | Decode, |
| 18 | } |
| 19 | |
| 20 | type Spent = [Duration; 4]; |
| 21 | |
| 22 | static SPENT: LazyLock<Mutex<HashMap<ThreadId, (Group, Duration)>>> = |
| 23 | LazyLock::new(Default::default); |
| 24 | |
| 25 | pub fn tick(group: Group) { |
| 26 | let Ok(time) = ThreadTime::try_now() else { |
| 27 | return; |
| 28 | }; |
| 29 | if let Ok(mut spent) = SPENT.lock() { |
| 30 | spent.insert(thread::current().id(), (group, time.as_duration())); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn spent() -> Option<Spent> { |
| 35 | let spent = SPENT.lock().ok()?; |
| 36 | let mut total = Spent::default(); |
| 37 | for (group, time) in spent.values() { |
| 38 | total[*group as usize] += *time; |
| 39 | } |
| 40 | Some(total) |
| 41 | } |
| 42 | |
| 43 | #[derive(Default)] |
| 44 | pub struct Sampler { |
| 45 | previous: Option<(Instant, Spent)>, |
| 46 | } |
| 47 | |
| 48 | impl Sampler { |
| 49 | pub fn sample(&mut self, cores: f32) -> Option<Threads> { |
| 50 | let now = (Instant::now(), spent()?); |
| 51 | let (at, then) = self.previous.replace(now)?; |
| 52 | let seconds = now.0.duration_since(at).as_secs_f32().max(f32::EPSILON) * cores; |
| 53 | let cpu = |group: Group| { |
| 54 | let index = group as usize; |
| 55 | now.1[index].saturating_sub(then[index]).as_secs_f32() * 100. / seconds |
| 56 | }; |
| 57 | Some(Threads { |
| 58 | gui: cpu(Group::Gui), |
| 59 | camera: cpu(Group::Camera), |
| 60 | encode: cpu(Group::Encode), |
| 61 | decode: cpu(Group::Decode), |
| 62 | }) |
| 63 | } |
| 64 | } |