Skip to content

Commit

Permalink
Implement Display trait (solana-labs#6929)
Browse files Browse the repository at this point in the history
  • Loading branch information
mvines authored Nov 13, 2019
1 parent a3a830e commit 18a17cf
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions measure/src/measure.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use solana_sdk::timing::duration_as_ns;
use std::time::Instant;
use std::{fmt, time::Instant};

pub struct Measure {
name: &'static str,
start: Instant,
duration: u64,
}

impl Measure {
pub fn start(_name: &'static str) -> Self {
pub fn start(name: &'static str) -> Self {
Self {
name,
start: Instant::now(),
duration: 0,
}
Expand All @@ -31,6 +33,22 @@ impl Measure {
}
}

impl fmt::Display for Measure {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.duration == 0 {
write!(f, "{} running", self.name)
} else if self.as_us() < 1 {
write!(f, "{} took {}ns", self.name, self.duration)
} else if self.as_ms() < 1 {
write!(f, "{} took {}us", self.name, self.as_us())
} else if self.as_s() < 1. {
write!(f, "{} took {}ms", self.name, self.as_ms())
} else {
write!(f, "{} took {:.1}s", self.name, self.as_s())
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -46,4 +64,38 @@ mod tests {
assert!(measure.as_ms() >= 990 && measure.as_ms() <= 1_010);
assert!(measure.as_us() >= 999_000 && measure.as_us() <= 1_010_000);
}

#[test]
fn test_measure_display() {
let measure = Measure {
name: "test_ns",
start: Instant::now(),
duration: 1,
};
assert_eq!(format!("{}", measure), "test_ns took 1ns");

let measure = Measure {
name: "test_us",
start: Instant::now(),
duration: 1000,
};
assert_eq!(format!("{}", measure), "test_us took 1us");

let measure = Measure {
name: "test_ms",
start: Instant::now(),
duration: 1000 * 1000,
};
assert_eq!(format!("{}", measure), "test_ms took 1ms");

let measure = Measure {
name: "test_s",
start: Instant::now(),
duration: 1000 * 1000 * 1000,
};
assert_eq!(format!("{}", measure), "test_s took 1.0s");

let measure = Measure::start("test_not_stopped");
assert_eq!(format!("{}", measure), "test_not_stopped running");
}
}

0 comments on commit 18a17cf

Please sign in to comment.