summaryrefslogtreecommitdiffstats
path: root/openpgp/src/macros.rs
diff options
context:
space:
mode:
authorNeal H. Walfield <neal@pep.foundation>2019-01-29 14:54:39 +0100
committerNeal H. Walfield <neal@pep.foundation>2019-01-29 14:58:53 +0100
commite53bddfb440f2b26e27c4c911d446f39db51cd09 (patch)
treeba71296515b74c231fb5c6131c77fb71a3b137ce /openpgp/src/macros.rs
parentc0936f19c299cd31b33ca568fd7a5304eb20ba2b (diff)
openpgp: Add a macro to profile a block of code.
- A macro to make profiling a few bits of code straightforward.
Diffstat (limited to 'openpgp/src/macros.rs')
-rw-r--r--openpgp/src/macros.rs54
1 files changed, 54 insertions, 0 deletions
diff --git a/openpgp/src/macros.rs b/openpgp/src/macros.rs
index 6317a0fe..20aaa6e5 100644
--- a/openpgp/src/macros.rs
+++ b/openpgp/src/macros.rs
@@ -50,3 +50,57 @@ macro_rules! tracer {
}
}
}
+
+
+/// A very simple profiling tool.
+///
+/// Note: don't ever profile code that has not been compiled in
+/// release mode. There can be orders of magnitude difference in
+/// execution time between it and debug mode!
+///
+/// This macro measures the wall time it takes to execute the block.
+/// If the time is at least $ms_threshold (in milli-seconds), then it
+/// displays the output on stderr. The output is prefixed with label,
+/// if it is provided.
+///
+/// ```
+/// let result = time_it!("Some code", 10, {
+/// // Some code.
+/// 5
+/// });
+/// assert_eq!(result, 5);
+/// ```
+#[allow(unused_macros)]
+macro_rules! time_it {
+ ( $label:expr, $ms_threshold:expr, $body:expr ) => {{
+ use std::time::{SystemTime, Duration};
+
+ // We use drop so that code that uses non-local exits (e.g.,
+ // using break 'label) still works.
+ struct Timer {
+ start: SystemTime,
+ };
+ impl Drop for Timer {
+ fn drop(&mut self) {
+ let elapsed = self.start.elapsed();
+ if elapsed.clone().unwrap_or(Duration::from_millis($ms_threshold))
+ >= Duration::from_millis($ms_threshold)
+ {
+ if $label.len() > 0 {
+ eprint!("{}:", $label);
+ }
+ eprintln!("{}:{}: {:?}", file!(), line!(), elapsed);
+ }
+ }
+ }
+
+ let _start = Timer { start: SystemTime::now() };
+ $body
+ }};
+ ( $label:expr, $body:expr ) => {
+ time_it!($label, 0, $body)
+ };
+ ( $body:expr ) => {
+ time_it!("", $body)
+ };
+}