From b2408cbc8f50d226a3e23dd7a64b69d93c8b97bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dj8yf0=CE=BCl?= Date: Thu, 28 Sep 2023 16:52:45 +0300 Subject: [PATCH] chore: add bench to illustrate diff --- benchmarks/Cargo.toml | 4 +++ benchmarks/benches/object_length.rs | 55 +++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 benchmarks/benches/object_length.rs diff --git a/benchmarks/Cargo.toml b/benchmarks/Cargo.toml index 4e4da3193..aad6202b9 100644 --- a/benchmarks/Cargo.toml +++ b/benchmarks/Cargo.toml @@ -36,5 +36,9 @@ harness = false name = "maps_sets_inner_de" harness = false +[[bench]] +name = "object_length" +harness = false + [features] default = ["borsh/std", "borsh/derive"] diff --git a/benchmarks/benches/object_length.rs b/benchmarks/benches/object_length.rs new file mode 100644 index 000000000..69a2c1826 --- /dev/null +++ b/benchmarks/benches/object_length.rs @@ -0,0 +1,55 @@ +use benchmarks::{Generate, ValidatorStake}; +use borsh::{to_vec, BorshDeserialize, BorshSerialize}; +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; +use rand::SeedableRng; + +fn ser_obj_length(group_name: &str, num_samples: usize, c: &mut Criterion) +where + for<'a> T: Generate + BorshSerialize + BorshDeserialize + 'static, +{ + let mut rng = rand_xorshift::XorShiftRng::from_seed([0u8; 16]); + let mut group = c.benchmark_group(group_name); + + let objects: Vec<_> = (0..num_samples).map(|_| T::generate(&mut rng)).collect(); + let borsh_datas: Vec> = objects.iter().map(|t| to_vec(t).unwrap()).collect(); + let borsh_sizes: Vec<_> = borsh_datas.iter().map(|d| d.len()).collect(); + + for i in 0..objects.len() { + let size = borsh_sizes[i]; + let obj = &objects[i]; + assert_eq!( + borsh::to_vec(obj).unwrap().len(), + borsh::object_length(obj).unwrap() + ); + + let benchmark_param_display = format!("idx={}; size={}", i, size); + + group.throughput(Throughput::Bytes(size as u64)); + group.bench_with_input( + BenchmarkId::new( + "borsh::to_vec(obj).unwrap().len()", + benchmark_param_display.clone(), + ), + obj, + |b, d| { + b.iter(|| borsh::to_vec(d).unwrap().len()); + }, + ); + group.bench_with_input( + BenchmarkId::new( + "borsh::object_length(obj).unwrap()", + benchmark_param_display.clone(), + ), + obj, + |b, d| { + b.iter(|| borsh::object_length(d).unwrap()); + }, + ); + } + group.finish(); +} +fn ser_length_validator_stake(c: &mut Criterion) { + ser_obj_length::("ser_account", 3, c); +} +criterion_group!(ser_length, ser_length_validator_stake,); +criterion_main!(ser_length);