Move most timing-related code to new module timer.rs
[mandelwow.git] / timer.rs
1 use std::time::{Duration, Instant};
2
3 #[derive(Debug)]
4 pub struct Timer {
5     pub t: f32,
6
7     frame: u32,
8
9     last_report_time: Instant,
10     last_report_frame: u32,
11
12     accum_draw_time: Duration,
13     accum_idle_time: Duration,
14
15     pub pause: bool,
16 }
17
18 impl Timer {
19     pub fn new() -> Self {
20         let now = Instant::now();
21         Timer {
22             t: 0.0,
23             frame: 0,
24             last_report_time: now,
25             last_report_frame: 0,
26             accum_draw_time: Duration::default(),
27             accum_idle_time: Duration::default(),
28             pause: false,
29         }
30     }
31
32     pub fn update(&mut self) {
33         let now = Instant::now();
34         if !self.pause {
35             // Increment time
36             self.t += 0.01;
37             self.frame += 1;
38         }
39         self.maybe_report(now);
40     }
41
42     #[cfg(not(feature = "logging"))]
43     fn maybe_report(&mut self, _: Instant) {}
44
45     #[cfg(feature = "logging")]
46     fn maybe_report(&mut self, now: Instant) {
47         if now - self.last_report_time > Duration::from_secs(5) {
48             self.report(now);
49             self.last_report_time = now;
50             self.last_report_frame = self.frame;
51             self.accum_draw_time = Duration::new(0, 0);
52             self.accum_idle_time = Duration::new(0, 0);
53         }
54     }
55
56     #[cfg(feature = "logging")]
57     fn report(&self, now: Instant) {
58         fn millis(d : Duration) -> f32 {
59             d.as_secs() as f32 * 1e3 + d.subsec_nanos() as f32 / 1e6
60         }
61         let frames_done = self.frame - self.last_report_frame;
62         let fps = frames_done as f32 / (now - self.last_report_time).as_secs() as f32;
63         let avg_draw_time = millis(self.accum_draw_time / frames_done);
64         let avg_idle_time = millis(self.accum_idle_time / frames_done);
65         println!("fps={:.1} draw={:.1}ms idle={:.1}ms", fps, avg_draw_time, avg_idle_time);
66     }
67 }