pfs-time-measure initial commit

A library to quickly measure the time for some code.
This commit is contained in:
ddidderr 2022-03-10 16:42:14 +01:00
commit 6b58daa9cd
Signed by: ddidderr
GPG Key ID: 3841F1C27E6F0E14
3 changed files with 106 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

8
Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "pfs-time-measure"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

96
src/lib.rs Normal file
View File

@ -0,0 +1,96 @@
use std::time::{Duration, Instant};
struct Measurement {
start: Instant,
finish: Instant,
}
pub struct Clock {
name: String,
start: Option<Instant>,
total_duration: Duration,
measurements: Vec<Measurement>,
}
impl Clock {
pub fn new(name: String, immediately_start: bool) -> Clock {
let start = if immediately_start {
Some(Instant::now())
} else {
None
};
Clock {
name,
start,
total_duration: Duration::default(),
measurements: Vec::with_capacity(16),
}
}
pub fn restart(&mut self) {
self.start = Some(Instant::now());
}
pub fn stop(&mut self) -> Option<Duration> {
if !self.is_running() {
return None;
}
// get duration of this measurement
let finish = Instant::now();
let duration = finish.duration_since(self.start.unwrap());
// add duration to total duration
self.total_duration += duration;
// add measurement to list of measurements
self.measurements.push(Measurement {
start: self.start.unwrap(),
finish: finish,
});
// reset
self.start = None;
// return duration of this specific measurement
Some(duration)
}
pub fn stop_and_print(&mut self) {
match self.stop() {
Some(duration) => self.print_duration(duration),
None => println!(
"[CLOCK] {} cannot be stopped because timer wasn't running",
self.name
),
}
}
fn is_running(&self) -> bool {
self.start.is_some()
}
fn print_duration(&self, duration: Duration) {
let name = &self.name;
let duration = duration.as_millis();
let total_duration = self.total_duration.as_millis();
println!("[CLOCK] {name} took {duration}ms (total {total_duration}ms)");
}
pub fn print_total(&self) {
self.print_duration(self.total_duration);
}
pub fn print_all_measurements(&self) {
for (idx, measurement) in self.measurements.iter().enumerate() {
println!(
"[CLOCK] {}/{}: {}ms",
self.name,
idx,
measurement.finish.duration_since(measurement.start).as_millis()
);
}
println!("[CLOCK] {}/total: {}ms", self.name, self.total_duration.as_millis());
}
}