Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@justanotherdot
Created August 13, 2020 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justanotherdot/fe4bf2024d2c13e3eace4f8d6730c3d1 to your computer and use it in GitHub Desktop.
Save justanotherdot/fe4bf2024d2c13e3eace4f8d6730c3d1 to your computer and use it in GitHub Desktop.
/*
If you look, I've also included a pattern to pass the number of times you want
the benchmark to run. I default to ten runs instead of one-hundred here as code
under inspection may take a long time to run under one-hundred times. You will
notice that I'm using nanoseconds for everything, which lets me compute a
proper mean average without rounding.
*/
macro_rules! bench {
($val:expr) => {
{
let mut mean = 0;
let times = 10;
for _ in 0..times {
let beg = std::time::Instant::now();
match $val {
_ => {
let end = std::time::Instant::now();
mean += (end - beg).as_nanos();
}
}
}
mean /= times;
eprintln!("[{}:{}] `{}' took {} ns after {} runs", std::file!(), std::line!(), std::stringify!($val), mean, times);
$val
}
};
($val:expr, $times:expr) => {
{
let mut mean = 0;
for _ in 0..$times {
let beg = std::time::Instant::now();
match $val {
_ => {
let end = std::time::Instant::now();
mean += (end - beg).as_nanos();
}
}
}
mean /= $times;
eprintln!("[{}:{}] `{}' took {} ns after {} runs", std::file!(), std::line!(), std::stringify!($val), mean, $times);
$val
}
};
($($val:expr),+ $(,)?) => {
($(bench!($val)),+,)
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment