1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
use std::time::*;
/// Timer sturct to retrieve current time
///
/// # Example
///
/// ```ignore
/// let mut timer = Timer::new();
/// println!("Time: {}", time.time());
///
/// std::time::sleep(Duration::from_secs(10));
/// time.update();
/// println!("Time: {}", time.time());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Timer {
pub(crate) instant: Instant,
pub(crate) current_frame: f32,
}
impl Timer {
/// Creates a new instance of the Time struct
///
/// # Example
///
/// ```ignore
/// let timer = Timer::new();
/// ```
pub fn new() -> Self {
return Self {
instant: Instant::now(),
current_frame: 0.0f32,
};
}
/// Updates the Timer struct's time
///
/// # Example
///
/// ```ignore
/// let mut timer = Timer::new();
///
/// std::time::sleep(Duration::from_secs(5));
///
/// timer.update();
/// ```
pub fn update(&mut self) {
self.current_frame = self.time();
}
/// Retrieves the delta time. (dt() function updates the this instance as well)
///
/// # Example
///
/// ```ignore
/// let mut timer = Timer::new();
/// std::time::sleep(Duration::from_secs(10));
/// timer.update();
/// std::time::sleep(Duration::from_secs(10));
/// println!("dt: {}", time.dt());
/// ```
pub fn dt(&mut self) -> f32 {
let current_frame = self.time();
let dt = current_frame - self.current_frame;
self.update();
return dt;
}
/// Retrieves the last time when an instance was updated
///
/// # Example
///
/// ```ignore
/// let mut timer = Timer::new();
/// assert_eq!(timer.current_frame(), 0.0);
///
/// std::time::sleep(Duration::from_secs(10));
/// assert_eq!(timer.current_frame(), 0.0);
///
/// timer.update();
/// assert_neq!(timer.current_frame(), 0.0);
/// ```
pub fn current_frame(&self) -> f32 {
return self.current_frame;
}
/// Retrieves the exact current time
///
/// # Example
///
/// ```ignore
/// let mut timer = Timer::new();
///
/// for _ in .. {
/// println!("Current time: {}", timer.time());
/// }
/// ```
pub fn time(&self) -> f32 {
return self.instant.elapsed().as_secs_f32();
}
}