Is it possible to use std
for benchmarks? If not, how can I get timestamps in a benchmark?
I tried using this but it didn't compile:
#[cfg(feature = "runtime-benchmarks")] extern crate std;
Substrate and Polkadot Stack Exchange is a question and answer site for developers building blockchains with the Substrate SDK. It only takes a minute to sign up.
Sign up to join this communityIs it possible to use std
for benchmarks? If not, how can I get timestamps in a benchmark?
I tried using this but it didn't compile:
#[cfg(feature = "runtime-benchmarks")] extern crate std;
You should use your benchmarking setup to insert a fake timestamp into your runtime, and use that for the execution of your code. Similar to how you would insert fake balances or other storage items into your benchmarking setup in order to properly execute the benchmark.
As you can see, the set_timestamp
function is made available to benchmarks: https://github.com/paritytech/substrate/blob/master/frame/timestamp/src/lib.rs#L283
impl<T: Config> Pallet<T> {
/// Get the current time for the current block.
///
/// NOTE: if this function is called prior to setting the timestamp,
/// it will return the timestamp of the previous block.
pub fn get() -> T::Moment {
Self::now()
}
/// Set the timestamp to something in particular. Only used for tests.
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
pub fn set_timestamp(now: T::Moment) {
Now::<T>::put(now);
DidUpdate::<T>::put(true);
<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
}
}
You can get the on-chain time from the timestamp pallet with Timestamp::now()
.
But this does not make sense for benchmarking. Benchmarks and their code run in WASM no-std. There are two ways this goes:
std
:
The code will therefore never be part of the runtime. Use criterion or any other benchmarking library you like and optimize it.no-std
:
This part is covered by FRAME
benchmarking. It records timestamps before and after executing the WASM code and calculates the weight of it.So I don't see why you want mix std
timestamps + FRAME
benchmarking.