#![cfg_attr(not(feature = "std"), no_std)]
mod tests;
mod utils;
#[cfg(feature = "std")]
mod analysis;
pub use utils::*;
#[cfg(feature = "std")]
pub use analysis::{Analysis, BenchmarkSelector};
#[doc(hidden)]
pub use sp_io::storage::root as storage_root;
pub use sp_runtime::traits::Zero;
pub use frame_support;
pub use paste;
pub use sp_storage::TrackedStorageKey;
#[macro_export]
macro_rules! benchmarks {
(
$( where_clause { where $( $where_ty:ty: $where_bound:path ),* $(,)? } )?
_ {
$(
let $common:ident in $common_from:tt .. $common_to:expr => $common_instancer:expr;
)*
}
$( $rest:tt )*
) => {
$crate::benchmarks_iter!(
{ }
{ $( $( $where_ty: $where_bound ),* )? }
{ $( { $common , $common_from , $common_to , $common_instancer } )* }
( )
( )
$( $rest )*
);
}
}
#[macro_export]
macro_rules! benchmarks_instance {
(
$( where_clause { where $( $where_ty:ty: $where_bound:path ),* $(,)? } )?
_ {
$(
let $common:ident in $common_from:tt .. $common_to:expr => $common_instancer:expr;
)*
}
$( $rest:tt )*
) => {
$crate::benchmarks_iter!(
{ I }
{ $( $( $where_ty: $where_bound ),* )? }
{ $( { $common , $common_from , $common_to , $common_instancer } )* }
( )
( )
$( $rest )*
);
}
}
#[macro_export]
#[doc(hidden)]
macro_rules! benchmarks_iter {
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
#[extra]
$name:ident
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* $name )
$name
$( $rest )*
}
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: _ ( $origin:expr $( , $arg:expr )* )
verify $postcode:block
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* )
$name { $( $code )* }: $name ( $origin $( , $arg )* )
verify $postcode
$( $rest )*
}
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: $dispatch:ident ( $origin:expr $( , $arg:expr )* )
verify $postcode:block
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* )
$name { $( $code )* }: {
<
Call<T $(, $instance)? > as $crate::frame_support::traits::UnfilteredDispatchable
>::dispatch_bypass_filter(
Call::<T $(, $instance)? >::$dispatch($($arg),*), $origin.into()
)?;
}
verify $postcode
$( $rest )*
}
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: $eval:block
verify $postcode:block
$( $rest:tt )*
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{ }
{ $eval }
{ $( $code )* }
$postcode
}
#[cfg(test)]
$crate::impl_benchmark_test!(
{ $( $where_clause )* }
{ $( $instance)? }
$name
);
$crate::benchmarks_iter!(
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* { $( $instance )? } $name )
( $( $names_extra )* )
$( $rest )*
);
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
) => {
$crate::selected_benchmark!(
{ $( $where_clause)* }
{ $( $instance)? }
$( $names )*
);
$crate::impl_benchmark!(
{ $( $where_clause )* }
{ $( $instance)? }
( $( $names )* )
( $( $names_extra ),* )
);
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: _ ( $origin:expr $( , $arg:expr )* )
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* )
$name { $( $code )* }: _ ( $origin $( , $arg )* )
verify { }
$( $rest )*
}
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: $dispatch:ident ( $origin:expr $( , $arg:expr )* )
$( $rest:tt )*
) => {
$crate::benchmarks_iter! {
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* )
$name { $( $code )* }: $dispatch ( $origin $( , $arg )* )
verify { }
$( $rest )*
}
};
(
{ $( $instance:ident )? }
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
( $( $names:tt )* )
( $( $names_extra:tt )* )
$name:ident { $( $code:tt )* }: $eval:block
$( $rest:tt )*
) => {
$crate::benchmarks_iter!(
{ $( $instance)? }
{ $( $where_clause )* }
{ $( $common )* }
( $( $names )* )
( $( $names_extra )* )
$name { $( $code )* }: $eval
verify { }
$( $rest )*
);
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! benchmark_backend {
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
{ $( PRE { $( $pre_parsed:tt )* } )* }
{ $eval:block }
{
let $pre_id:tt : $pre_ty:ty = $pre_ex:expr;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{
$( PRE { $( $pre_parsed )* } )*
PRE { $pre_id , $pre_ty , $pre_ex }
}
{ $eval }
{ $( $rest )* }
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $param:ident in ( $param_from:expr ) .. $param_to:expr => $param_instancer:expr;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{
$( $parsed )*
PARAM { $param , $param_from , $param_to , $param_instancer }
}
{ $eval }
{ $( $rest )* }
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $param:ident in ...;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( { $common , $common_from , $common_to , $common_instancer } )* }
{ $( $parsed )* }
{ $eval }
{
let $param
in ({ $( let $common = $common_from; )* $param })
.. ({ $( let $common = $common_to; )* $param })
=> ({ $( let $common = || -> Result<(), &'static str> { $common_instancer ; Ok(()) }; )* $param()? });
$( $rest )*
}
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $param:ident in _ .. _ => $param_instancer:expr ;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( { $common , $common_from , $common_to , $common_instancer } )* }
{ $( $parsed )* }
{ $eval }
{
let $param
in ({ $( let $common = $common_from; )* $param })
.. ({ $( let $common = $common_to; )* $param })
=> $param_instancer ;
$( $rest )*
}
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $param:ident in $param_from:tt .. $param_to:expr => $param_instancer:expr ;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{ $( $parsed )* }
{ $eval }
{
let $param in ( $param_from ) .. $param_to => $param_instancer;
$( $rest )*
}
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $param:ident in $param_from:tt .. $param_to:expr;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{ $( $parsed )* }
{ $eval }
{
let $param in $param_from .. $param_to => ();
$( $rest )*
}
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( $common:tt )* }
{ $( $parsed:tt )* }
{ $eval:block }
{
let $pre_id:tt = $pre_ex:expr;
$( $rest:tt )*
}
$postcode:block
) => {
$crate::benchmark_backend! {
{ $( $instance)? }
$name
{ $( $where_clause )* }
{ $( $common )* }
{ $( $parsed )* }
{ $eval }
{
let $pre_id : _ = $pre_ex;
$( $rest )*
}
$postcode
}
};
(
{ $( $instance:ident )? }
$name:ident
{ $( $where_clause:tt )* }
{ $( { $common:ident , $common_from:tt , $common_to:expr , $common_instancer:expr } )* }
{
$( PRE { $pre_id:tt , $pre_ty:ty , $pre_ex:expr } )*
$( PARAM { $param:ident , $param_from:expr , $param_to:expr , $param_instancer:expr } )*
}
{ $eval:block }
{ $( $post:tt )* }
$postcode:block
) => {
#[allow(non_camel_case_types)]
struct $name;
#[allow(unused_variables)]
impl<T: Trait $( <$instance>, I: Instance)? >
$crate::BenchmarkingSetup<T $(, $instance)? > for $name
where $( $where_clause )*
{
fn components(&self) -> Vec<($crate::BenchmarkParameter, u32, u32)> {
vec! [
$(
($crate::BenchmarkParameter::$param, $param_from, $param_to)
),*
]
}
fn instance(
&self,
components: &[($crate::BenchmarkParameter, u32)],
verify: bool
) -> Result<Box<dyn FnOnce() -> Result<(), &'static str>>, &'static str> {
$(
let $common = $common_from;
)*
$(
let $param = components.iter()
.find(|&c| c.0 == $crate::BenchmarkParameter::$param)
.ok_or("Could not find component in benchmark preparation.")?
.1;
)*
$(
let $pre_id : $pre_ty = $pre_ex;
)*
$( $param_instancer ; )*
$( $post )*
Ok(Box::new(move || -> Result<(), &'static str> {
$eval;
if verify {
$postcode;
}
Ok(())
}))
}
}
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! selected_benchmark {
(
{ $( $where_clause:tt )* }
{ $( $instance:ident )? }
$( { $( $bench_inst:ident )? } $bench:ident )*
) => {
#[allow(non_camel_case_types)]
enum SelectedBenchmark {
$( $bench, )*
}
impl<T: Trait $( <$instance>, I: Instance )? >
$crate::BenchmarkingSetup<T $(, $instance )? > for SelectedBenchmark
where $( $where_clause )*
{
fn components(&self) -> Vec<($crate::BenchmarkParameter, u32, u32)> {
match self {
$(
Self::$bench => <
$bench as $crate::BenchmarkingSetup<T $(, $bench_inst)? >
>::components(&$bench),
)*
}
}
fn instance(
&self,
components: &[($crate::BenchmarkParameter, u32)],
verify: bool
) -> Result<Box<dyn FnOnce() -> Result<(), &'static str>>, &'static str> {
match self {
$(
Self::$bench => <
$bench as $crate::BenchmarkingSetup<T $(, $bench_inst)? >
>::instance(&$bench, components, verify),
)*
}
}
}
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! impl_benchmark {
(
{ $( $where_clause:tt )* }
{ $( $instance:ident )? }
( $( { $( $name_inst:ident )? } $name:ident )* )
( $( $name_extra:ident ),* )
) => {
impl<T: Trait $(<$instance>, I: Instance)? >
$crate::Benchmarking<$crate::BenchmarkResults> for Module<T $(, $instance)? >
where T: frame_system::Trait, $( $where_clause )*
{
fn benchmarks(extra: bool) -> Vec<&'static [u8]> {
let mut all = vec![ $( stringify!($name).as_ref() ),* ];
if !extra {
let extra = [ $( stringify!($name_extra).as_ref() ),* ];
all.retain(|x| !extra.contains(x));
}
all
}
fn run_benchmark(
extrinsic: &[u8],
lowest_range_values: &[u32],
highest_range_values: &[u32],
steps: &[u32],
repeat: u32,
whitelist: &[$crate::TrackedStorageKey],
verify: bool,
) -> Result<Vec<$crate::BenchmarkResults>, &'static str> {
let extrinsic = sp_std::str::from_utf8(extrinsic)
.map_err(|_| "`extrinsic` is not a valid utf8 string!")?;
let selected_benchmark = match extrinsic {
$( stringify!($name) => SelectedBenchmark::$name, )*
_ => return Err("Could not find extrinsic."),
};
let mut results: Vec<$crate::BenchmarkResults> = Vec::new();
if repeat == 0 {
return Ok(results);
}
let mut whitelist = whitelist.to_vec();
let whitelisted_caller_key =
<frame_system::Account::<T> as frame_support::storage::StorageMap<_,_>>::hashed_key_for(
$crate::whitelisted_caller::<T::AccountId>()
);
whitelist.push(whitelisted_caller_key.into());
$crate::benchmarking::set_whitelist(whitelist);
$crate::benchmarking::commit_db();
$crate::benchmarking::wipe_db();
let components = <
SelectedBenchmark as $crate::BenchmarkingSetup<T $(, $instance)?>
>::components(&selected_benchmark);
let mut prev_steps = 10;
let repeat_benchmark = |
repeat: u32,
c: &[($crate::BenchmarkParameter, u32)],
results: &mut Vec<$crate::BenchmarkResults>,
verify: bool,
| -> Result<(), &'static str> {
for _ in 0..repeat {
let closure_to_benchmark = <
SelectedBenchmark as $crate::BenchmarkingSetup<T $(, $instance)?>
>::instance(&selected_benchmark, c, verify)?;
if $crate::Zero::is_zero(&frame_system::Module::<T>::block_number()) {
frame_system::Module::<T>::set_block_number(1u32.into());
}
$crate::benchmarking::commit_db();
$crate::benchmarking::reset_read_write_count();
if verify {
closure_to_benchmark()?;
} else {
frame_support::debug::trace!(
target: "benchmark",
"Start Benchmark: {:?}", c
);
let start_extrinsic = $crate::benchmarking::current_time();
closure_to_benchmark()?;
let finish_extrinsic = $crate::benchmarking::current_time();
let elapsed_extrinsic = finish_extrinsic - start_extrinsic;
$crate::benchmarking::commit_db();
frame_support::debug::trace!(
target: "benchmark",
"End Benchmark: {} ns", elapsed_extrinsic
);
let read_write_count = $crate::benchmarking::read_write_count();
frame_support::debug::trace!(
target: "benchmark",
"Read/Write Count {:?}", read_write_count
);
let start_storage_root = $crate::benchmarking::current_time();
$crate::storage_root();
let finish_storage_root = $crate::benchmarking::current_time();
let elapsed_storage_root = finish_storage_root - start_storage_root;
results.push($crate::BenchmarkResults {
components: c.to_vec(),
extrinsic_time: elapsed_extrinsic,
storage_root_time: elapsed_storage_root,
reads: read_write_count.0,
repeat_reads: read_write_count.1,
writes: read_write_count.2,
repeat_writes: read_write_count.3,
});
}
$crate::benchmarking::wipe_db();
}
Ok(())
};
if components.is_empty() {
if verify {
repeat_benchmark(1, Default::default(), &mut Vec::new(), true)?;
}
repeat_benchmark(repeat, Default::default(), &mut results, false)?;
} else {
for (idx, (name, low, high)) in components.iter().enumerate() {
let steps = steps.get(idx).cloned().unwrap_or(prev_steps);
prev_steps = steps;
if steps == 0 { continue }
let lowest = lowest_range_values.get(idx).cloned().unwrap_or(*low);
let highest = highest_range_values.get(idx).cloned().unwrap_or(*high);
let diff = highest - lowest;
let step_size = (diff / steps).max(1);
let num_of_steps = diff / step_size + 1;
for s in 0..num_of_steps {
let component_value = lowest + step_size * s;
let c: Vec<($crate::BenchmarkParameter, u32)> = components.iter()
.enumerate()
.map(|(idx, (n, _, h))|
if n == name {
(*n, component_value)
} else {
(*n, *highest_range_values.get(idx).unwrap_or(h))
}
)
.collect();
if verify {
repeat_benchmark(1, &c, &mut Vec::new(), true)?;
}
repeat_benchmark(repeat, &c, &mut results, false)?;
}
}
}
return Ok(results);
}
}
};
}
#[macro_export]
#[doc(hidden)]
macro_rules! impl_benchmark_test {
(
{ $( $where_clause:tt )* }
{ $( $instance:ident )? }
$name:ident
) => {
$crate::paste::item! {
fn [<test_benchmark_ $name>] <T: Trait > () -> Result<(), &'static str>
where T: frame_system::Trait, $( $where_clause )*
{
let selected_benchmark = SelectedBenchmark::$name;
let components = <
SelectedBenchmark as $crate::BenchmarkingSetup<T, _>
>::components(&selected_benchmark);
let execute_benchmark = |
c: Vec<($crate::BenchmarkParameter, u32)>
| -> Result<(), &'static str> {
let closure_to_verify = <
SelectedBenchmark as $crate::BenchmarkingSetup<T, _>
>::instance(&selected_benchmark, &c, true)?;
if $crate::Zero::is_zero(&frame_system::Module::<T>::block_number()) {
frame_system::Module::<T>::set_block_number(1u32.into());
}
closure_to_verify()?;
$crate::benchmarking::wipe_db();
Ok(())
};
if components.is_empty() {
execute_benchmark(Default::default())?;
} else {
for (_, (name, low, high)) in components.iter().enumerate() {
for component_value in vec![low, high] {
let c: Vec<($crate::BenchmarkParameter, u32)> = components.iter()
.enumerate()
.map(|(_, (n, _, h))|
if n == name {
(*n, *component_value)
} else {
(*n, *h)
}
)
.collect();
execute_benchmark(c)?;
}
}
}
Ok(())
}
}
};
}
#[macro_export]
macro_rules! add_benchmark {
( $params:ident, $batches:ident, $name:ident, $( $location:tt )* ) => (
let name_string = stringify!($name).as_bytes();
let (config, whitelist) = $params;
let $crate::BenchmarkConfig {
pallet,
benchmark,
lowest_range_values,
highest_range_values,
steps,
repeat,
verify,
extra,
} = config;
if &pallet[..] == &name_string[..] || &pallet[..] == &b"*"[..] {
if &pallet[..] == &b"*"[..] || &benchmark[..] == &b"*"[..] {
for benchmark in $( $location )*::benchmarks(*extra).into_iter() {
$batches.push($crate::BenchmarkBatch {
results: $( $location )*::run_benchmark(
benchmark,
&lowest_range_values[..],
&highest_range_values[..],
&steps[..],
*repeat,
whitelist,
*verify,
)?,
pallet: name_string.to_vec(),
benchmark: benchmark.to_vec(),
});
}
} else {
$batches.push($crate::BenchmarkBatch {
results: $( $location )*::run_benchmark(
&benchmark[..],
&lowest_range_values[..],
&highest_range_values[..],
&steps[..],
*repeat,
whitelist,
*verify,
)?,
pallet: name_string.to_vec(),
benchmark: benchmark.clone(),
});
}
}
)
}