Created
August 22, 2021 09:50
-
-
Save Akanoa/abebaff00ad52dd7e13dbdfb46bf0eb3 to your computer and use it in GitHub Desktop.
A simple Time Tracker in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct TimeTracker { | |
start: Instant, | |
name: &'static str, | |
} | |
impl TimeTracker { | |
fn new(name: &'static str) -> Self { | |
TimeTracker { | |
start: Instant::now(), | |
name, | |
} | |
} | |
} | |
impl Drop for TimeTracker { | |
fn drop(&mut self) { | |
let elapsed = Instant::now().duration_since(self.start); | |
println!("{} took {:?}", self.name, elapsed) | |
} | |
} | |
mod tests { | |
use std::thread; | |
use std::time::Duration; | |
use crate::TimeTracker; | |
#[test] | |
fn test_time_tracker() { | |
let _time_tracker = TimeTracker::new("time tracker"); | |
thread::sleep(Duration::from_secs(10)) | |
// display: time tracker took 10.012828s | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When the
_time_tracker
goes out of the scope, the drop function of the TimeTracker instance is launched.