687f3e424a86d090431c335b5cfb196545bb5476
[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 //! It utilizes the `time` crate.
3
4 /// This function will measure how long it takes to execute the given lambda,
5 /// print the time and return the result of the lambda.
6 pub fn report_time<Out, F: FnOnce() -> Out>(name: &str, f: F) -> Out {
7     let start = time::now();
8     eprintln!("starting {}", name);
9     let res = f();
10     eprintln!("done {} - took: {}", name, (time::now() - start));
11     res
12 }
13
14 /// This function will measure how long it takes to execute the given lambda
15 /// and return a tuple of the result of the lambda and a duration object.
16 pub fn measure<Out, F: FnOnce() -> Out>(f: F) -> (Out, time::Duration) {
17     let start = time::now();
18     let res = f();
19     (res, time::now() - start)
20 }
21
22 /// A struct to repeatedly measure the time passed since the timer was started
23 #[derive(Debug)]
24 pub struct Timer {
25     start: time::Tm
26 }
27
28 impl Default for Timer {
29     fn default() -> Self {
30         Self::new()
31     }
32 }
33
34 impl Timer {
35     /// Create and start a new `Timer`
36     pub fn new() -> Timer {
37         Timer { start: time::now() }
38     }
39
40     /// Reset the `Timer`
41     pub fn restart(&mut self) {
42         self.start = time::now();
43     }
44
45     /// Print the passed time in ms since the timer was started
46     pub fn report_passed_ms(&self) {
47         eprintln!("{}ms", (time::now() - self.start).num_milliseconds());
48     }
49
50     /// Return the number of ms passed since the timer was started as a `i64`
51     pub fn get_passed_ms(&self) -> i64 {
52         (time::now() - self.start).num_milliseconds()
53     }
54 }