Skip to content

Instantly share code, notes, and snippets.

@Akanoa
Created August 22, 2021 09:50
Show Gist options
  • Save Akanoa/abebaff00ad52dd7e13dbdfb46bf0eb3 to your computer and use it in GitHub Desktop.
Save Akanoa/abebaff00ad52dd7e13dbdfb46bf0eb3 to your computer and use it in GitHub Desktop.
A simple Time Tracker in Rust
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
}
}
@Akanoa
Copy link
Author

Akanoa commented Aug 22, 2021

When the _time_tracker goes out of the scope, the drop function of the TimeTracker instance is launched.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment