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
use std::time::SystemTime;
use crate::{here, Error, ErrorLocation, Location};
#[must_use]
pub struct Timing {
now: SystemTime,
}
impl Default for Timing {
fn default() -> Self {
Self::new()
}
}
impl Timing {
pub fn new() -> Self {
Self {
now: SystemTime::now(),
}
}
#[inline]
pub fn elapsed(&mut self) -> Result<String, Error> {
let result = self.elapsed_str().location(here!())?;
self.now = SystemTime::now();
Ok(result)
}
#[inline]
fn elapsed_str(&self) -> Result<String, Error> {
let time = self.now.elapsed().location(here!())?;
let mut elapsed = time.as_millis();
let mut unit = "ms";
if elapsed <= 1 {
elapsed = time.as_micros();
unit = "μs";
}
if elapsed <= 1 {
elapsed = time.as_nanos();
unit = "ns";
}
Ok(format!("{}{}", elapsed, unit))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timing() -> Result<(), Error> {
let mut timing = Timing::new();
let _ = timing.elapsed()?;
Ok(())
}
}