twgpu_tools/
dbg.rs

1#![allow(unused)]
2
3use std::time;
4
5pub struct BusyTimer {
6    name: String,
7    iterations_to_stats: u32,
8    iteration_index: u32,
9    state: Option<State>,
10    busy_time: u64,
11    sleep_time: u64,
12    clock: time::Instant,
13}
14
15#[derive(Debug, PartialEq)]
16enum State {
17    Busy,
18    Sleep,
19}
20
21impl BusyTimer {
22    pub fn new(name: String, iterations_to_stats: u32) -> Self {
23        assert_eq!(iterations_to_stats & 1, 0);
24        Self {
25            name,
26            iterations_to_stats,
27            iteration_index: 0,
28            state: None,
29            busy_time: 0,
30            sleep_time: 0,
31            clock: time::Instant::now(),
32        }
33    }
34
35    pub fn busy(&mut self) {
36        assert_ne!(self.state, Some(State::Busy));
37        if self.state.is_some() {
38            self.sleep_time += self.reset_get_micros();
39        }
40        self.state = Some(State::Busy);
41    }
42
43    pub fn sleeping(&mut self) {
44        assert_ne!(self.state, Some(State::Sleep));
45        if self.state.is_some() {
46            self.busy_time += self.reset_get_micros();
47        }
48        self.state = Some(State::Sleep);
49    }
50
51    fn reset_get_micros(&mut self) -> u64 {
52        self.iteration_index += 1;
53        if self.iteration_index == self.iterations_to_stats {
54            self.iteration_index = 0;
55            let busy_micros = self.busy_time as f64;
56            let total_micros = (self.busy_time + self.sleep_time) as f64;
57
58            let percentage = (busy_micros / total_micros) * 100.;
59            eprintln!("DBG: Thread {} busy time: {percentage:.0}%", self.name);
60
61            self.busy_time = 0;
62            self.sleep_time = 0;
63        }
64        let micros = self.clock.elapsed().as_micros();
65        self.clock = time::Instant::now();
66        micros as u64
67    }
68}