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