simple_stopwatch/
lib.rs

1//! # simple-stopwatch
2//!
3//! A minimal no-thrills stopwatch. Returns time values as floats. Uses time::precise_time_ns under the hood.
4
5extern crate time;
6
7/// Simple stopwatch
8#[derive(Clone, Copy)]
9pub struct Stopwatch {
10    /// Start time in ns
11    start_time_ns: u64,
12}
13
14impl Stopwatch {
15    /// Create new stopwatch and start timing
16    pub fn start_new() -> Stopwatch {
17        Stopwatch {
18            start_time_ns: time::precise_time_ns(),
19        }
20    }
21
22    /// Restart timing from current time
23    ///
24    /// # Examples
25    ///
26    /// ```
27    /// use simple_stopwatch::Stopwatch;
28    /// use std::time::Duration;
29    ///
30    /// fn main() {
31    ///     let mut sw = Stopwatch::start_new();
32    ///
33    ///     // emulate some work
34    ///     std::thread::sleep(Duration::from_millis(1000));
35    ///
36    ///     sw.restart();
37    ///
38    ///     let ms = sw.ms();
39    ///     assert!( ms < 1f32, "After restart, timer value is small" );
40    /// }
41    /// ```
42    pub fn restart(&mut self) {
43        *self = Stopwatch::start_new();
44    }
45
46    /// Get elapsed time since creation/restart in seconds
47    pub fn s(&self) -> f32 {
48        (time::precise_time_ns() - self.start_time_ns) as f32 / 1000000000f32
49    }
50
51    /// Get elapsed time since creation/restart in milliseconds
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use simple_stopwatch::Stopwatch;
57    /// use std::time::Duration;
58    ///
59    /// fn main() {
60    ///     let mut sw = Stopwatch::start_new();
61    ///
62    ///     // emulate some work
63    ///     std::thread::sleep(Duration::from_millis(10));
64    ///
65    ///     // measure elapsed time
66    ///     let ms = sw.ms();
67    ///     assert!( ms >= 10f32 );
68    /// }
69    /// ```
70    pub fn ms(&self) -> f32 {
71        (time::precise_time_ns() - self.start_time_ns) as f32 / 1000000f32
72    }
73
74    /// Get elapsed time since creation/restart in microseconds
75    pub fn us(&self) -> f32 {
76        (time::precise_time_ns() - self.start_time_ns) as f32 / 1000f32
77    }
78
79    /// Get elapsed time since creation/restart in nanoseconds
80    pub fn ns(&self) -> f32 {
81        (time::precise_time_ns() - self.start_time_ns) as f32
82    }
83}