1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use core::convert::TryInto;
use std::{
collections::{HashMap, HashSet},
fs,
path::PathBuf,
};
use inflector::Inflector;
use serde::Serialize;
use crate::BenchmarkCmd;
use frame_benchmarking::{
Analysis, AnalysisChoice, BenchmarkBatchSplitResults, BenchmarkResults, BenchmarkSelector,
RegressionModel,
};
use frame_support::traits::StorageInfo;
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::Zero;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const TEMPLATE: &str = include_str!("./template.hbs");
#[derive(Serialize, Default, Debug, Clone)]
struct TemplateData {
args: Vec<String>,
date: String,
version: String,
pallet: String,
instance: String,
header: String,
cmd: CmdData,
benchmarks: Vec<BenchmarkData>,
}
#[derive(Serialize, Default, Debug, Clone)]
struct BenchmarkData {
name: String,
components: Vec<Component>,
#[serde(serialize_with = "string_serialize")]
base_weight: u128,
#[serde(serialize_with = "string_serialize")]
base_reads: u128,
#[serde(serialize_with = "string_serialize")]
base_writes: u128,
component_weight: Vec<ComponentSlope>,
component_reads: Vec<ComponentSlope>,
component_writes: Vec<ComponentSlope>,
comments: Vec<String>,
}
#[derive(Serialize, Default, Debug, Clone)]
struct CmdData {
steps: u32,
repeat: u32,
lowest_range_values: Vec<u32>,
highest_range_values: Vec<u32>,
execution: String,
wasm_execution: String,
chain: String,
db_cache: u32,
analysis_choice: String,
}
#[derive(Serialize, Debug, Clone, Eq, PartialEq)]
struct Component {
name: String,
is_used: bool,
}
#[derive(Serialize, Debug, Clone, Eq, PartialEq)]
struct ComponentSlope {
name: String,
#[serde(serialize_with = "string_serialize")]
slope: u128,
#[serde(serialize_with = "string_serialize")]
error: u128,
}
fn io_error(s: &str) -> std::io::Error {
use std::io::{Error, ErrorKind};
Error::new(ErrorKind::Other, s)
}
fn map_results(
batches: &[BenchmarkBatchSplitResults],
storage_info: &[StorageInfo],
analysis_choice: &AnalysisChoice,
) -> Result<HashMap<(String, String), Vec<BenchmarkData>>, std::io::Error> {
if batches.is_empty() {
return Err(io_error("empty batches"))
}
let mut all_benchmarks = HashMap::new();
let mut pallet_benchmarks = Vec::new();
let mut batches_iter = batches.iter().peekable();
while let Some(batch) = batches_iter.next() {
if batch.time_results.is_empty() {
continue
}
let pallet_string = String::from_utf8(batch.pallet.clone()).unwrap();
let instance_string = String::from_utf8(batch.instance.clone()).unwrap();
let benchmark_data = get_benchmark_data(batch, storage_info, analysis_choice);
pallet_benchmarks.push(benchmark_data);
if let Some(next) = batches_iter.peek() {
let next_pallet = String::from_utf8(next.pallet.clone()).unwrap();
let next_instance = String::from_utf8(next.instance.clone()).unwrap();
if next_pallet != pallet_string || next_instance != instance_string {
all_benchmarks.insert((pallet_string, instance_string), pallet_benchmarks.clone());
pallet_benchmarks = Vec::new();
}
} else {
all_benchmarks.insert((pallet_string, instance_string), pallet_benchmarks.clone());
}
}
Ok(all_benchmarks)
}
fn extract_errors(model: &Option<RegressionModel>) -> impl Iterator<Item = u128> + '_ {
let mut errors = model.as_ref().map(|m| m.se.regressor_values.iter());
std::iter::from_fn(move || match &mut errors {
Some(model) => model.next().map(|val| *val as u128),
_ => Some(0),
})
}
fn get_benchmark_data(
batch: &BenchmarkBatchSplitResults,
storage_info: &[StorageInfo],
analysis_choice: &AnalysisChoice,
) -> BenchmarkData {
let mut comments = Vec::<String>::new();
let analysis_function = match analysis_choice {
AnalysisChoice::MinSquares => Analysis::min_squares_iqr,
AnalysisChoice::MedianSlopes => Analysis::median_slopes,
AnalysisChoice::Max => Analysis::max,
};
let extrinsic_time = analysis_function(&batch.time_results, BenchmarkSelector::ExtrinsicTime)
.expect("analysis function should return an extrinsic time for valid inputs");
let reads = analysis_function(&batch.db_results, BenchmarkSelector::Reads)
.expect("analysis function should return the number of reads for valid inputs");
let writes = analysis_function(&batch.db_results, BenchmarkSelector::Writes)
.expect("analysis function should return the number of writes for valid inputs");
let mut used_components = Vec::new();
let mut used_extrinsic_time = Vec::new();
let mut used_reads = Vec::new();
let mut used_writes = Vec::new();
extrinsic_time
.slopes
.into_iter()
.zip(extrinsic_time.names.iter())
.zip(extract_errors(&extrinsic_time.model))
.for_each(|((slope, name), error)| {
if !slope.is_zero() {
if !used_components.contains(&name) {
used_components.push(name);
}
used_extrinsic_time.push(ComponentSlope {
name: name.clone(),
slope: slope.saturating_mul(1000),
error: error.saturating_mul(1000),
});
}
});
reads
.slopes
.into_iter()
.zip(reads.names.iter())
.zip(extract_errors(&reads.model))
.for_each(|((slope, name), error)| {
if !slope.is_zero() {
if !used_components.contains(&name) {
used_components.push(name);
}
used_reads.push(ComponentSlope { name: name.clone(), slope, error });
}
});
writes
.slopes
.into_iter()
.zip(writes.names.iter())
.zip(extract_errors(&writes.model))
.for_each(|((slope, name), error)| {
if !slope.is_zero() {
if !used_components.contains(&name) {
used_components.push(name);
}
used_writes.push(ComponentSlope { name: name.clone(), slope, error });
}
});
let components = batch.time_results[0]
.components
.iter()
.map(|(name, _)| -> Component {
let name_string = name.to_string();
let is_used = used_components.contains(&&name_string);
Component { name: name_string, is_used }
})
.collect::<Vec<_>>();
add_storage_comments(&mut comments, &batch.db_results, storage_info);
BenchmarkData {
name: String::from_utf8(batch.benchmark.clone()).unwrap(),
components,
base_weight: extrinsic_time.base.saturating_mul(1000),
base_reads: reads.base,
base_writes: writes.base,
component_weight: used_extrinsic_time,
component_reads: used_reads,
component_writes: used_writes,
comments,
}
}
pub fn write_results(
batches: &[BenchmarkBatchSplitResults],
storage_info: &[StorageInfo],
path: &PathBuf,
cmd: &BenchmarkCmd,
) -> Result<(), std::io::Error> {
let template: String = match &cmd.template {
Some(template_file) => fs::read_to_string(template_file)?,
None => TEMPLATE.to_string(),
};
let header_text = match &cmd.header {
Some(header_file) => {
let text = fs::read_to_string(header_file)?;
text
},
None => String::new(),
};
let date = chrono::Utc::now().format("%Y-%m-%d").to_string();
let args = std::env::args().collect::<Vec<String>>();
let analysis_choice: AnalysisChoice =
cmd.output_analysis.clone().try_into().map_err(|e| io_error(e))?;
let cmd_data = CmdData {
steps: cmd.steps.clone(),
repeat: cmd.repeat.clone(),
lowest_range_values: cmd.lowest_range_values.clone(),
highest_range_values: cmd.highest_range_values.clone(),
execution: format!("{:?}", cmd.execution),
wasm_execution: cmd.wasm_method.to_string(),
chain: format!("{:?}", cmd.shared_params.chain),
db_cache: cmd.database_cache_size,
analysis_choice: format!("{:?}", analysis_choice),
};
let mut handlebars = handlebars::Handlebars::new();
handlebars.register_helper("underscore", Box::new(UnderscoreHelper));
handlebars.register_helper("join", Box::new(JoinHelper));
handlebars.register_escape_fn(|s| -> String { s.to_string() });
let all_results = map_results(batches, storage_info, &analysis_choice)?;
for ((pallet, instance), results) in all_results.iter() {
let mut file_path = path.clone();
if file_path.is_dir() {
if all_results.keys().any(|(p, i)| p == pallet && i != instance) {
file_path.push(pallet.clone() + "_" + &instance.to_snake_case());
} else {
file_path.push(pallet.clone());
}
file_path.set_extension("rs");
}
let hbs_data = TemplateData {
args: args.clone(),
date: date.clone(),
version: VERSION.to_string(),
pallet: pallet.to_string(),
instance: instance.to_string(),
header: header_text.clone(),
cmd: cmd_data.clone(),
benchmarks: results.clone(),
};
let mut output_file = fs::File::create(file_path)?;
handlebars
.render_template_to_write(&template, &hbs_data, &mut output_file)
.map_err(|e| io_error(&e.to_string()))?;
}
Ok(())
}
fn add_storage_comments(
comments: &mut Vec<String>,
results: &[BenchmarkResults],
storage_info: &[StorageInfo],
) {
let mut storage_info_map = storage_info
.iter()
.map(|info| (info.prefix.clone(), info))
.collect::<HashMap<_, _>>();
let skip_storage_info = StorageInfo {
pallet_name: b"Skipped".to_vec(),
storage_name: b"Metadata".to_vec(),
prefix: b"Skipped Metadata".to_vec(),
max_values: None,
max_size: None,
};
storage_info_map.insert(skip_storage_info.prefix.clone(), &skip_storage_info);
let mut identified = HashSet::<Vec<u8>>::new();
for result in results.clone() {
for (key, reads, writes, whitelisted) in &result.keys {
if *whitelisted {
continue
}
let prefix_length = key.len().min(32);
let prefix = key[0..prefix_length].to_vec();
if identified.contains(&prefix) {
continue
} else {
identified.insert(prefix.clone());
}
match storage_info_map.get(&prefix) {
Some(key_info) => {
let comment = format!(
"Storage: {} {} (r:{} w:{})",
String::from_utf8(key_info.pallet_name.clone())
.expect("encoded from string"),
String::from_utf8(key_info.storage_name.clone())
.expect("encoded from string"),
reads,
writes,
);
comments.push(comment)
},
None => {
let comment = format!(
"Storage: unknown [0x{}] (r:{} w:{})",
HexDisplay::from(key),
reads,
writes,
);
comments.push(comment)
},
}
}
}
}
fn underscore<Number>(i: Number) -> String
where
Number: std::string::ToString,
{
let mut s = String::new();
let i_str = i.to_string();
let a = i_str.chars().rev().enumerate();
for (idx, val) in a {
if idx != 0 && idx % 3 == 0 {
s.insert(0, '_');
}
s.insert(0, val);
}
s
}
#[derive(Clone, Copy)]
struct UnderscoreHelper;
impl handlebars::HelperDef for UnderscoreHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &handlebars::Helper,
_: &handlebars::Handlebars,
_: &handlebars::Context,
_rc: &mut handlebars::RenderContext,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
use handlebars::JsonRender;
let param = h.param(0).unwrap();
let underscore_param = underscore(param.value().render());
out.write(&underscore_param)?;
Ok(())
}
}
#[derive(Clone, Copy)]
struct JoinHelper;
impl handlebars::HelperDef for JoinHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &handlebars::Helper,
_: &handlebars::Handlebars,
_: &handlebars::Context,
_rc: &mut handlebars::RenderContext,
out: &mut dyn handlebars::Output,
) -> handlebars::HelperResult {
use handlebars::JsonRender;
let param = h.param(0).unwrap();
let value = param.value();
let joined = if value.is_array() {
value
.as_array()
.unwrap()
.iter()
.map(|v| v.render())
.collect::<Vec<String>>()
.join(" ")
} else {
value.render()
};
out.write(&joined)?;
Ok(())
}
}
fn string_serialize<S>(x: &u128, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.serialize_str(&x.to_string())
}
#[cfg(test)]
mod test {
use super::*;
use frame_benchmarking::{BenchmarkBatchSplitResults, BenchmarkParameter, BenchmarkResults};
fn test_data(
pallet: &[u8],
benchmark: &[u8],
param: BenchmarkParameter,
base: u32,
slope: u32,
) -> BenchmarkBatchSplitResults {
let mut results = Vec::new();
for i in 0..5 {
results.push(BenchmarkResults {
components: vec![(param, i), (BenchmarkParameter::z, 0)],
extrinsic_time: (base + slope * i).into(),
storage_root_time: (base + slope * i).into(),
reads: (base + slope * i).into(),
repeat_reads: 0,
writes: (base + slope * i).into(),
repeat_writes: 0,
proof_size: 0,
keys: vec![],
})
}
return BenchmarkBatchSplitResults {
pallet: [pallet.to_vec(), b"_pallet".to_vec()].concat(),
instance: b"instance".to_vec(),
benchmark: [benchmark.to_vec(), b"_benchmark".to_vec()].concat(),
time_results: results.clone(),
db_results: results,
}
}
fn check_data(benchmark: &BenchmarkData, component: &str, base: u128, slope: u128) {
assert_eq!(
benchmark.components,
vec![
Component { name: component.to_string(), is_used: true },
Component { name: "z".to_string(), is_used: false },
],
);
assert_eq!(benchmark.base_weight, base * 1_000);
assert_eq!(
benchmark.component_weight,
vec![ComponentSlope { name: component.to_string(), slope: slope * 1_000, error: 0 }]
);
assert_eq!(benchmark.base_reads, base);
assert_eq!(
benchmark.component_reads,
vec![ComponentSlope { name: component.to_string(), slope, error: 0 }]
);
assert_eq!(benchmark.base_writes, base);
assert_eq!(
benchmark.component_writes,
vec![ComponentSlope { name: component.to_string(), slope, error: 0 }]
);
}
#[test]
fn map_results_works() {
let mapped_results = map_results(
&[
test_data(b"first", b"first", BenchmarkParameter::a, 10, 3),
test_data(b"first", b"second", BenchmarkParameter::b, 9, 2),
test_data(b"second", b"first", BenchmarkParameter::c, 3, 4),
],
&[],
&AnalysisChoice::default(),
)
.unwrap();
let first_benchmark = &mapped_results
.get(&("first_pallet".to_string(), "instance".to_string()))
.unwrap()[0];
assert_eq!(first_benchmark.name, "first_benchmark");
check_data(first_benchmark, "a", 10, 3);
let second_benchmark = &mapped_results
.get(&("first_pallet".to_string(), "instance".to_string()))
.unwrap()[1];
assert_eq!(second_benchmark.name, "second_benchmark");
check_data(second_benchmark, "b", 9, 2);
let second_pallet_benchmark = &mapped_results
.get(&("second_pallet".to_string(), "instance".to_string()))
.unwrap()[0];
assert_eq!(second_pallet_benchmark.name, "first_benchmark");
check_data(second_pallet_benchmark, "c", 3, 4);
}
}