Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
e62e1ed
init weight_meter
ermalkaleci Mar 11, 2021
1ee5d69
update meter static var
ermalkaleci Mar 11, 2021
9250171
update workspace
ermalkaleci Mar 11, 2021
8f85cf8
fmt
ermalkaleci Mar 11, 2021
61615e5
clippy allow unused imports
ermalkaleci Mar 11, 2021
8b465d9
default std
ermalkaleci Mar 11, 2021
8e40a04
update cargo
ermalkaleci Mar 11, 2021
04f659b
remove std
ermalkaleci Mar 11, 2021
8edec36
revert until fix no_std issue
ermalkaleci Mar 12, 2021
41136b8
improvements
ermalkaleci Mar 12, 2021
1485035
fmt
ermalkaleci Mar 12, 2021
0d6c751
update argument extract
ermalkaleci Mar 12, 2021
135d43d
package name with orml prefix
ermalkaleci Mar 12, 2021
c6040e1
update meter to be Mutex
ermalkaleci Mar 15, 2021
c8d7d73
use mutex only in std
ermalkaleci Mar 15, 2021
b857553
update README
ermalkaleci Mar 15, 2021
d7a3af0
update README
ermalkaleci Mar 15, 2021
c5ab5a4
update property name
ermalkaleci Mar 16, 2021
5dadd78
separate method injector
ermalkaleci Mar 16, 2021
46a7969
docs
ermalkaleci Mar 16, 2021
d46f3d4
fmt
ermalkaleci Mar 16, 2021
3116627
clippy
ermalkaleci Mar 16, 2021
9245ede
Orml bencher (#452)
brettkolodny Apr 15, 2021
2c253fa
fix bencher dependencies
ermalkaleci Apr 16, 2021
4d21e02
Weight meter (#459)
brettkolodny Apr 21, 2021
db799bc
fix
xlc Apr 21, 2021
7dc337e
Updated frame-support version (#461)
brettkolodny Apr 22, 2021
bb2e1ad
Merge branch 'master' of github.com:open-web3-stack/open-runtime-modu…
ermalkaleci May 5, 2021
b516ee1
clippy
brettkolodny May 5, 2021
89db2f7
fmt
brettkolodny May 5, 2021
7a9a4e8
fix
xlc May 5, 2021
161d4c0
switched to thread_local
brettkolodny May 5, 2021
d0b1bfa
Added checked add
brettkolodny May 6, 2021
7015576
corrected versions
brettkolodny May 6, 2021
24eb2d8
weight_meter tests
brettkolodny May 10, 2021
1f25e71
Removed starting weight
brettkolodny May 11, 2021
21e3ed4
Removed method_benchmark/updated inner docs
brettkolodny May 11, 2021
4ac388e
clippy and fmt
brettkolodny May 12, 2021
a19888d
changed start_with to start
brettkolodny May 14, 2021
5cc9ad6
Merge branch 'master' of https://github.com/open-web3-stack/open-runt…
brettkolodny May 14, 2021
6f029fa
Changed start_with to start in macro
brettkolodny May 14, 2021
ec787cb
cleanup
ermalkaleci May 17, 2021
223046a
refactor
ermalkaleci May 17, 2021
529a79c
fix clippy
ermalkaleci May 17, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.dev.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ cargo-features = ["resolver"]
members = [
"auction",
"authority",
"bencher",
"benchmarking",
"currencies",
"gradually-update",
Expand All @@ -20,6 +21,8 @@ members = [
# "xcm-support",
# "unknown-tokens",
"build-script-utils",
"weight-gen",
"weight-meter",
]
resolver = "2"

Expand Down Expand Up @@ -67,6 +70,7 @@ sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev
sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sc-executor-wasmi = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sc-executor = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sc-client-db = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sp-tasks = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "3f110196163b5ec03bac5ee188d60bedf3ebd91d" }
Expand Down
39 changes: 39 additions & 0 deletions bencher/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
[package]
name = "orml-bencher"
description = "Provide macro to benchmark pallets."
repository = "https://github.com/open-web3-stack/open-runtime-module-library/tree/master/bencher"
license = "Apache-2.0"
version = "0.4.1-dev"
authors = ["Laminar Developers <hello@laminar.one>"]
edition = "2018"

[dependencies]
linregress = { version = "0.4.0", optional = true }
serde = { version = "1.0.119", optional = true, features = ['derive'] }
serde_json = {version = "1.0.64", optional = true }
codec = { package = "parity-scale-codec", version = "2.0.0", features = ["derive"], default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false }
sp-runtime-interface = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false }
sp-state-machine = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false, optional = true }
sc-executor = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false, features = ["wasmtime"], optional = true }
sc-client-db = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false, features = ["with-kvdb-rocksdb"], optional = true }
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "rococo-v1", default-features = false }

[features]
default = ["std"]
std = [
"linregress",
"serde/std",
"serde_json/std",
"codec/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
"sp-runtime-interface/std",
"sp-state-machine/std",
"sc-executor/std",
"sc-client-db",
"frame-benchmarking/std",
]
39 changes: 39 additions & 0 deletions bencher/src/bench_runner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use frame_benchmarking::{
benchmarking,
frame_support::sp_runtime::traits::{Block, NumberFor},
};
use sc_client_db::BenchmarkingState;
use sc_executor::{sp_wasm_interface::HostFunctions, WasmExecutionMethod, WasmExecutor};
use sp_core::traits::{CallInWasm, MissingHostFunctions};
use sp_io::SubstrateHostFunctions;
use sp_state_machine::{Ext, OverlayedChanges, StorageTransactionCache};

/// Run benches
pub fn run<B: Block>(wasm_code: Vec<u8>) -> Vec<u8> {
let mut overlay = OverlayedChanges::default();
let mut cache = StorageTransactionCache::default();
let state = BenchmarkingState::<B>::new(Default::default(), Default::default(), false).unwrap();
let mut ext = Ext::<_, NumberFor<B>, _>::new(&mut overlay, &mut cache, &state, None, None);

let mut host_functions = benchmarking::HostFunctions::host_functions();
host_functions.append(&mut SubstrateHostFunctions::host_functions());

let executor = WasmExecutor::new(
WasmExecutionMethod::Compiled,
Default::default(),
host_functions,
1,
None,
);

executor
.call_in_wasm(
&wasm_code[..],
None,
"run_benches",
&[],
&mut ext,
MissingHostFunctions::Disallow,
)
.unwrap()
}
54 changes: 54 additions & 0 deletions bencher/src/handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use crate::BenchResult;
use codec::Decode;
use linregress::{FormulaRegressionBuilder, RegressionDataBuilder};
use serde::{Deserialize, Serialize};
use std::io::Write;

#[derive(Serialize, Deserialize, Default, Debug, Clone)]
struct BenchData {
pub name: String,
pub base_weight: u64,
pub base_reads: u32,
pub base_writes: u32,
}

/// Handle bench results
pub fn handle(output: Vec<u8>) {
let results = <Vec<BenchResult> as Decode>::decode(&mut &output[..]).unwrap();
let data: Vec<BenchData> = results
.into_iter()
.map(|result| {
let name = String::from_utf8_lossy(&result.method).to_string();

eprintln!("{:#?}", result);

let y: Vec<f64> = result.elapses.into_iter().map(|x| x as f64).collect();
let x: Vec<f64> = (0..y.len()).into_iter().map(|x| x as f64).collect();
let data = vec![("Y", y), ("X", x)];
let data = RegressionDataBuilder::new().build_from(data).unwrap();
let formula = "Y ~ X";

let model = FormulaRegressionBuilder::new()
.data(&data)
.formula(formula)
.fit()
.unwrap();

BenchData {
name,
base_weight: model.parameters.intercept_value as u64 * 1_000,
base_reads: result.reads,
base_writes: result.writes,
}
})
.collect();

if let Ok(json) = serde_json::to_string(&data) {
let stdout = ::std::io::stdout();
let mut handle = stdout.lock();

handle.write_all(&json.as_bytes()).unwrap();
} else {
eprintln!("Could not write benchdata to JSON");
}
}
28 changes: 28 additions & 0 deletions bencher/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#![cfg_attr(not(feature = "std"), no_std)]

#[doc(hidden)]
pub extern crate frame_benchmarking;
#[doc(hidden)]
pub extern crate sp_core;
#[doc(hidden)]
pub extern crate sp_std;

use codec::{Decode, Encode};
use sp_std::prelude::Vec;

#[derive(Encode, Decode, Default, Clone, PartialEq, Debug)]
pub struct BenchResult {
pub method: Vec<u8>,
pub elapses: Vec<u128>,
pub reads: u32,
pub repeat_reads: u32,
pub writes: u32,
pub repeat_writes: u32,
}

mod macros;

#[cfg(feature = "std")]
pub mod bench_runner;
#[cfg(feature = "std")]
pub mod handler;
160 changes: 160 additions & 0 deletions bencher/src/macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/// Run benches in WASM environment.
///
/// Configure your module to build the mock runtime into wasm code.
/// Create a `build.rs` like you do with your runtime.
/// ```.ignore
/// use substrate_wasm_builder::WasmBuilder;
/// fn main() {
/// WasmBuilder::new()
/// .with_current_project()
/// .export_heap_base()
/// .import_memory()
/// .build()
/// }
/// ```
///
/// Update mock runtime to be build into wasm code.
/// ```.ignore
/// #![cfg_attr(not(feature = "std"), no_std)]
///
/// #[cfg(feature = "std")]
/// include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
///
/// #[cfg(feature = "std")]
/// pub fn wasm_binary_unwrap() -> &'static [u8] { WASM_BINARY.unwrap() }
/// ..
/// ```
///
/// Create a file `bench_runner.rs` with following code:
/// ```.ignore
/// orml_bencher::run_benches!(my_module::benches);
/// ```
///
/// Update Cargo.toml by adding:
/// ```toml
/// ..
/// [package]
/// name = "my-module"
/// ..
/// build = 'build.rs'
///
/// [build-dependencies]
/// substrate-wasm-builder = '4.0.0'
///
/// [[bench]]
/// name = 'benches'
/// harness = false
/// path = 'bench_runner.rs'
/// required-features = ['bench']
///
/// [features]
/// bench = []
/// ..
/// ```
///
/// Run bench with features bench: `cargo bench --features=bench`
#[cfg(feature = "std")]
#[macro_export]
macro_rules! run_benches {
($benches:path) => {
use $benches::{wasm_binary_unwrap, Block};
pub fn main() {
let output = $crate::bench_runner::run::<Block>(wasm_binary_unwrap().to_vec());
$crate::handler::handle(output);
}
};
}

/// Define benches
///
/// Create a file `src/benches.rs`:
/// ```.ignore
/// #![cfg_attr(not(feature = "std"), no_std)]
/// #![allow(dead_code)]
///
/// #[cfg(feature = "std")] // Re-export for bench_runner
/// pub use crate::mock::{Block, wasm_binary_unwrap};
///
/// use crate::mock::YourModule;
///
/// fn foo(b: &mut Bencher) {
/// b.bench("foo", || {
/// YourModule::foo();
/// });
/// }
///
/// fn bar(b: &mut Bencher) {
/// b.bench("bar", || {
/// YourModule::bar();
/// });
/// }
///
/// orml_bencher::bench!(foo, bar);
/// ```
/// Update `src/lib.rs`:
/// ```.ignore
/// #[cfg(any(feature = "bench", test))]
/// pub mod mock; /* mock runtime needs to be compiled into wasm */
/// #[cfg(feature = "bench")]
/// pub mod benches;
/// ```
#[macro_export]
macro_rules! bench {
(
$($method:path),+
) => {
use $crate::BenchResult;
use $crate::sp_std::{cmp::max, prelude::Vec};
use $crate::frame_benchmarking::{benchmarking, BenchmarkResults};

#[derive(Default, Clone, PartialEq, Debug)]
struct Bencher {
pub results: Vec<BenchResult>,
}

impl Bencher {
pub fn bench<F: Fn() -> ()>(&mut self, name: &str, block: F) {
// Warm up the DB
benchmarking::commit_db();
benchmarking::wipe_db();

let mut result = BenchResult {
method: name.as_bytes().to_vec(),
..Default::default()
};

for _ in 0..50 {
benchmarking::commit_db();
benchmarking::reset_read_write_count();

let start_time = benchmarking::current_time();
block();
let end_time = benchmarking::current_time();
let elasped = end_time - start_time;
result.elapses.push(elasped);

benchmarking::commit_db();
let (reads, repeat_reads, writes, repeat_writes) = benchmarking::read_write_count();

result.reads = max(result.reads, reads);
result.repeat_reads = max(result.repeat_reads, repeat_reads);
result.writes = max(result.writes, writes);
result.repeat_writes = max(result.repeat_writes, repeat_writes);

benchmarking::wipe_db();
}
self.results.push(result);
}
}

$crate::sp_core::wasm_export_functions! {
fn run_benches() -> Vec<BenchResult> {
let mut bencher = Bencher::default();
$(
$method(&mut bencher);
)+
bencher.results
}
}
}
}
17 changes: 17 additions & 0 deletions weight-gen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "weight-gen"
description = "CLI for generating weight from bencher output"
license = "Apache-2.0"
version = "0.4.1-dev"
authors = ["Laminar Developers <hello@laminar.one>"]
edition = "2018"

[dependencies]
serde = { version = "1.0.119", features = ['derive'] }
serde_json = "1.0"
clap = "3.0.0-beta.2"
handlebars = { version = "3.5.2" }

[features]
default = ["std"]
std = []
Loading