X-Git-Url: https://i11git.iti.kit.edu/anon-gitweb/?p=Mitarbeiter%2FTim-Zeitz%2Fstud-rust-base.git;a=blobdiff_plain;f=src%2Ftime.rs;h=687f3e424a86d090431c335b5cfb196545bb5476;hp=2f6e9ac3b59d40235d792b5dc35a43ed45279058;hb=HEAD;hpb=dd14e61875eedc443d6004db819562a9b7f98a14 diff --git a/src/time.rs b/src/time.rs index 2f6e9ac..33c720c 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,45 +1,60 @@ -use time_crate as time; +//! This module contains a few utilities to measure how long executing algorithms takes. -#[allow(dead_code)] +use std::time::*; + +/// This function will measure how long it takes to execute the given lambda, +/// print the time and return the result of the lambda. pub fn report_time Out>(name: &str, f: F) -> Out { - let start = time::now(); - println!("starting {}", name); + let start = Instant::now(); + eprintln!("starting {}", name); let res = f(); - println!("done {} - took: {}", name, (time::now() - start)); + eprintln!("done {} - took: {}s", name, start.elapsed().as_secs_f64()); res } -#[allow(dead_code)] -pub fn measure Out>(f: F) -> (Out, time::Duration) { - let start = time::now(); +/// This function will measure how long it takes to execute the given lambda +/// and return a tuple of the result of the lambda and a duration object. +pub fn measure Out>(f: F) -> (Out, Duration) { + let start = Instant::now(); let res = f(); - (res, time::now() - start) + (res, start.elapsed()) } -#[allow(dead_code)] +/// A struct to repeatedly measure the time passed since the timer was started #[derive(Debug)] pub struct Timer { - start: time::Tm + start: Instant, +} + +impl Default for Timer { + fn default() -> Self { + Self::new() + } } impl Timer { - #[allow(dead_code)] + /// Create and start a new `Timer` pub fn new() -> Timer { - Timer { start: time::now() } + Timer { start: Instant::now() } } - #[allow(dead_code)] + /// Reset the `Timer` pub fn restart(&mut self) { - self.start = time::now(); + self.start = Instant::now(); } - #[allow(dead_code)] + /// Print the passed time in ms since the timer was started pub fn report_passed_ms(&self) { - println!("{}ms", (time::now() - self.start).num_milliseconds()); + eprintln!("{}ms", self.start.elapsed().as_secs_f64() * 1000.0); + } + + /// Return the number of ms passed since the timer was started as a `i64` + pub fn get_passed_ms(&self) -> f64 { + self.start.elapsed().as_secs_f64() * 1000.0 } - #[allow(dead_code)] - pub fn get_passed_ms(&self) -> i64 { - (time::now() - self.start).num_milliseconds() + /// Return the number of ms passed since the timer was started as a `std::time::Duration` + pub fn get_passed(&self) -> Duration { + self.start.elapsed() } }