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
//! # simple-stopwatch //! //! A minimal no-thrills stopwatch. Returns time values as floats. Uses time::precise_time_ns under the hood. extern crate time; /// Simple stopwatch #[derive(Clone, Copy)] pub struct Stopwatch { /// Start time in ns start_time_ns: u64, } impl Stopwatch { /// Create new stopwatch and start timing pub fn start_new() -> Stopwatch { Stopwatch { start_time_ns: time::precise_time_ns(), } } /// Restart timing from current time /// /// # Examples /// /// ``` /// use simple_stopwatch::Stopwatch; /// use std::time::Duration; /// /// fn main() { /// let mut sw = Stopwatch::start_new(); /// /// // emulate some work /// std::thread::sleep(Duration::from_millis(1000)); /// /// sw.restart(); /// /// let ms = sw.ms(); /// assert!( ms < 1f32, "After restart, timer value is small" ); /// } /// ``` pub fn restart(&mut self) { *self = Stopwatch::start_new(); } /// Get elapsed time since creation/restart in seconds pub fn s(&self) -> f32 { (time::precise_time_ns() - self.start_time_ns) as f32 / 1000000000f32 } /// Get elapsed time since creation/restart in milliseconds /// /// # Examples /// /// ``` /// use simple_stopwatch::Stopwatch; /// use std::time::Duration; /// /// fn main() { /// let mut sw = Stopwatch::start_new(); /// /// // emulate some work /// std::thread::sleep(Duration::from_millis(10)); /// /// // measure elapsed time /// let ms = sw.ms(); /// assert!( ms >= 10f32 ); /// } /// ``` pub fn ms(&self) -> f32 { (time::precise_time_ns() - self.start_time_ns) as f32 / 1000000f32 } /// Get elapsed time since creation/restart in microseconds pub fn us(&self) -> f32 { (time::precise_time_ns() - self.start_time_ns) as f32 / 1000f32 } /// Get elapsed time since creation/restart in nanoseconds pub fn ns(&self) -> f32 { (time::precise_time_ns() - self.start_time_ns) as f32 } }