updates, clippy, formatting
[Mitarbeiter/Tim-Zeitz/stud-rust-base.git] / src / time.rs
1 //! This module contains a few utilities to measure how long executing algorithms takes.
2
3 use std::time::*;
4
5 /// This function will measure how long it takes to execute the given lambda,
6 /// print the time and return the result of the lambda.
7 pub fn report_time<Out, F: FnOnce() -> Out>(name: &str, f: F) -> Out {
8     let start = Instant::now();
9     eprintln!("starting {}", name);
10     let res = f();
11     eprintln!("done {} - took: {}s", name, start.elapsed().as_secs_f64());
12     res
13 }
14
15 /// This function will measure how long it takes to execute the given lambda
16 /// and return a tuple of the result of the lambda and a duration object.
17 pub fn measure<Out, F: FnOnce() -> Out>(f: F) -> (Out, Duration) {
18     let start = Instant::now();
19     let res = f();
20     (res, start.elapsed())
21 }
22
23 /// A struct to repeatedly measure the time passed since the timer was started
24 #[derive(Debug)]
25 pub struct Timer {
26     start: Instant,
27 }
28
29 impl Default for Timer {
30     fn default() -> Self {
31         Self::new()
32     }
33 }
34
35 impl Timer {
36     /// Create and start a new `Timer`
37     pub fn new() -> Timer {
38         Timer { start: Instant::now() }
39     }
40
41     /// Reset the `Timer`
42     pub fn restart(&mut self) {
43         self.start = Instant::now();
44     }
45
46     /// Print the passed time in ms since the timer was started
47     pub fn report_passed_ms(&self) {
48         eprintln!("{}ms", self.start.elapsed().as_secs_f64() * 1000.0);
49     }
50
51     /// Return the number of ms passed since the timer was started as a `i64`
52     pub fn get_passed_ms(&self) -> f64 {
53         self.start.elapsed().as_secs_f64() * 1000.0
54     }
55
56     /// Return the number of ms passed since the timer was started as a `std::time::Duration`
57     pub fn get_passed(&self) -> Duration {
58         self.start.elapsed()
59     }
60 }