trace_time/lib.rs
1// Copyright 2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Performance timer with logging
10
11use log::trace;
12use std::time::Instant;
13
14#[macro_export]
15macro_rules! trace_time {
16 ($name: expr) => {
17 let _timer = $crate::PerfTimer::new($name);
18 };
19}
20
21/// Performance timer with logging. Starts measuring time in the constructor, prints
22/// elapsed time in the destructor or when `stop` is called.
23pub struct PerfTimer {
24 name: &'static str,
25 start: Instant,
26}
27
28impl PerfTimer {
29 /// Create an instance with given name.
30 pub fn new(name: &'static str) -> PerfTimer {
31 PerfTimer { name, start: Instant::now() }
32 }
33}
34
35impl Drop for PerfTimer {
36 fn drop(&mut self) {
37 let elapsed = self.start.elapsed();
38 let ms = elapsed.as_millis();
39 trace!(target: "perf", "{}: {:.2}ms", self.name, ms);
40 }
41}