time_it: a Case Study in Rust Macros
My adventures in Declarative Macros Land
Problem setup
let timer = std::time::Instant::now();
let x = do_stuff();
println!("do_stuff: {:?}", timer.elapsed());
// Output:
// do_stuff: 2.12swith Timer("part 1"):
do_a()
do_b()
do_c()Macro for timing a single statement
macro_rules! time_it {
($context:literal, $s:stmt) => {
let timer = std::time::Instant::now();
$s
println!("{}: {:?}", $context, timer.elapsed());
};
}
// Let's test it:
fn main() {
time_it!("println", println!("hello, world!"));
let x = 1;
time_it!("let", let _y = x + 2);
}
/* This will print:
hello, world!
println: 31.143µs
let: 43ns
*/First nuance: `stmt` fragment specifier and semicolons
Second nuance: no semicolon in the expansion: `$s`
Handling multiple statements
With block specifier
With `stmt` repetitions
With `tt` specifier
Summary
PreviousMore advanced aspects of pattern matching in RustNextRust Closures: Returning `impl Fn` for `move` closures
Last updated