Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use time::SteadyTime;
- trait Stopwatch<'a> {
- type Guard: StopwatchGuard<'a>;
- fn start(&'a self) -> Self::Guard;
- }
- trait StopwatchGuard<'a> {
- fn sub(&'a self, name: impl AsRef<str>) -> Self;
- }
- struct Gauge;
- impl Gauge {
- pub fn set(&self, value: f64, name: &str) {
- println!("{}: {}", name, value);
- }
- }
- struct MyStopwatch {
- gauge: Gauge,
- }
- impl MyStopwatch {
- pub fn new() -> Self {
- Self {
- gauge: Gauge,
- }
- }
- }
- struct MyStopwatchGuard<'a> {
- stopwatch: &'a MyStopwatch,
- start: SteadyTime,
- name: String,
- }
- impl<'a> Drop for MyStopwatchGuard<'a> {
- fn drop(&mut self) {
- let now = SteadyTime::now();
- let millis = match (now - self.start).num_nanoseconds() {
- Some(nanos) => nanos as f64 / 1_000_000.,
- //None => 0., // if > 2^63 ns (292 years)
- None => std::i64::MAX as f64 / 1_000_000.,
- };
- self.stopwatch.gauge.set(millis, &self.name);
- }
- }
- impl<'a> StopwatchGuard<'a> for MyStopwatchGuard<'a> {
- fn sub(&self, name: impl AsRef<str>) -> Self {
- MyStopwatchGuard {
- stopwatch: self.stopwatch,
- start: SteadyTime::now(),
- name: format!("{}.{}", self.name, name.as_ref()),
- }
- }
- }
- impl<'a> Stopwatch<'a> for MyStopwatch {
- type Guard = MyStopwatchGuard<'a>;
- fn start(&'a self) -> Self::Guard {
- MyStopwatchGuard {
- start: SteadyTime::now(),
- stopwatch: self,
- name: "root".to_owned(),
- }
- }
- }
- fn sleep_ms(ms: u64) {
- std::thread::sleep(std::time::Duration::from_millis(ms))
- }
- fn main() {
- let s = MyStopwatch::new();
- let foo = s.start();
- sleep_ms(400);
- {
- let _bar = foo.sub("bar");
- sleep_ms(100);
- }
- {
- let baz = foo.sub("baz");
- sleep_ms(150);
- let _qux = baz.sub("qux");
- sleep_ms(150);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement