1use std::time::{Instant, Duration};
2
3pub struct Timer {
4 last_frame: Instant,
5 fps_counter: u32,
6 fps_timer: Instant,
7 current_fps: u32,
8}
9
10impl Timer {
11 pub fn new() -> Self {
12 let now = Instant::now();
13 Self {
14 last_frame: now,
15 fps_counter: 0,
16 fps_timer: now,
17 current_fps: 0,
18 }
19 }
20
21 pub fn delta_time(&mut self) -> f32 {
22 let now = Instant::now();
23 let delta = now.duration_since(self.last_frame).as_secs_f32();
24 self.last_frame = now;
25 delta
26 }
27
28 pub fn update_fps(&mut self) -> Option<u32> {
29 self.fps_counter += 1;
30 let elapsed = self.fps_timer.elapsed();
31
32 if elapsed >= Duration::from_secs(1) {
33 self.current_fps = self.fps_counter;
34 self.fps_counter = 0;
35 self.fps_timer = Instant::now();
36 Some(self.current_fps)
37 } else {
38 None
39 }
40 }
41
42 pub fn fps(&self) -> u32 {
43 self.current_fps
44 }
45}