Skip to content

Commit

Permalink
fix(benchmarks,runtime-interface): clear store by counter when runnin…
Browse files Browse the repository at this point in the history
…g benchmarks
  • Loading branch information
ByteNacked committed Aug 26, 2024
1 parent 5ad141e commit 4778ddd
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions pallets/gear/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ runtime-benchmarks = [
"frame-system/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"common/runtime-benchmarks",
"gear-runtime-interface/runtime-benchmarks",
"gear-core-backend/mock",
"gear-core-errors/codec",
"gear-sandbox",
Expand Down
3 changes: 3 additions & 0 deletions runtime-interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,6 @@ std = [
"ark-scale/std",
"sha2/std"
]
runtime-benchmarks = [
"gear-sandbox-interface/runtime-benchmarks"
]
1 change: 1 addition & 0 deletions runtime-interface/sandbox/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ std = [
"sp-runtime-interface/std",
"sp-wasm-interface/std",
]
runtime-benchmarks = []
28 changes: 28 additions & 0 deletions runtime-interface/sandbox/src/detail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ impl Sandboxes {

&mut self.store
}

// Clears the underlying store if the counter exceeds the limit.
#[cfg(feature = "runtime-benchmarks")]
pub fn clear(&mut self) {
BENCH_SANDBOX_RESET_COUNTER.with_borrow_mut(|c| {
if *c >= BENCH_SANDBOX_RESET_COUNTER_LIMIT {
*c = 0;
self.store.clear();
}
*c += 1;
});
}
}

thread_local! {
Expand Down Expand Up @@ -453,6 +465,14 @@ pub fn memory_new(context: &mut dyn FunctionContext, initial: u32, maximum: u32)

let data_ptr: *const _ = caller.data();
method_result = SANDBOXES.with(|sandboxes| {
// The usual method to clear the store doesn't work for benchmarks (see `Sanboxes::get`).
// This issue is more prominent in so-called "onetime syscall" benchmarks because
// they run with minimal steps and a large number of repeats, leading to significant slowdowns.
// Therefore, we have to clear it manually if the `BENCH_SANDBOX_RESET_COUNTER` exceeds the limit.
// Otherwise, the store becomes too big and will slow down the benchmarks.
#[cfg(feature = "runtime-benchmarks")]
sandboxes.borrow_mut().clear();

sandboxes
.borrow_mut()
.get(data_ptr as usize)
Expand Down Expand Up @@ -577,3 +597,11 @@ pub fn set_global_val(

method_result
}

#[cfg(feature = "runtime-benchmarks")]
const BENCH_SANDBOX_RESET_COUNTER_LIMIT: u32 = 100;

#[cfg(feature = "runtime-benchmarks")]
thread_local! {
static BENCH_SANDBOX_RESET_COUNTER: RefCell<u32> = const { RefCell::new(0) };
}

0 comments on commit 4778ddd

Please sign in to comment.