From fb08e1f94b33849333b61bfd22a31b947d69847e Mon Sep 17 00:00:00 2001 From: Martin Dahl Date: Wed, 13 Dec 2023 17:05:12 +0100 Subject: [PATCH] Add deserialization benchmark. --- r2r/Cargo.toml | 5 +++ r2r/benches/deserialization.rs | 57 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 r2r/benches/deserialization.rs diff --git a/r2r/Cargo.toml b/r2r/Cargo.toml index 39baf8ba6..76f9838cb 100644 --- a/r2r/Cargo.toml +++ b/r2r/Cargo.toml @@ -34,6 +34,7 @@ futures = "0.3.25" tokio = { version = "1.22.0", features = ["rt-multi-thread", "time", "macros"] } rand = "0.8.5" cdr = "0.2.4" +criterion = "0.5.1" [build-dependencies] r2r_common = { path = "../r2r_common", version = "0.8.2" } @@ -51,3 +52,7 @@ doc-only = ["r2r_common/doc-only", "r2r_rcl/doc-only", "r2r_msg_gen/doc-only", " [package.metadata.docs.rs] features = ["doc-only"] + +[[bench]] +name = "deserialization" +harness = false diff --git a/r2r/benches/deserialization.rs b/r2r/benches/deserialization.rs new file mode 100644 index 000000000..f81342b08 --- /dev/null +++ b/r2r/benches/deserialization.rs @@ -0,0 +1,57 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use r2r::*; +use rand::Rng; +use rand::thread_rng; + +const NUM_ELEMENTS: usize = 10_000; +const NUM_TIMES: usize = 1_000; + +fn bench_ros_deserialization() { + let mut rng = thread_rng(); + let mut numbers = Vec::::with_capacity(NUM_ELEMENTS); + + for _ in 0..NUM_ELEMENTS { + numbers.push(rng.gen_range(0..i32::MAX)); + } + let message = std_msgs::msg::Int32MultiArray { + layout: std_msgs::msg::MultiArrayLayout::default(), + data: numbers + }; + + let bytes = message.to_serialized_bytes().unwrap(); + + for _ in 0..NUM_TIMES { + let _ = std_msgs::msg::Int32MultiArray::from_serialized_bytes(&bytes).unwrap(); + } +} + +fn bench_cdr_deserialization() { + let mut rng = thread_rng(); + let mut numbers = Vec::::with_capacity(NUM_ELEMENTS); + + for _ in 0..NUM_ELEMENTS { + numbers.push(rng.gen_range(0..i32::MAX)); + } + let message = std_msgs::msg::Int32MultiArray { + layout: std_msgs::msg::MultiArrayLayout::default(), + data: numbers + }; + + let bytes = message.to_serialized_bytes().unwrap(); + + for _ in 0..NUM_TIMES { + let _msg1 = cdr::deserialize::(&bytes).unwrap(); + // just for testing that we get the same result. + // let msg2 = std_msgs::msg::Int32MultiArray::from_serialized_bytes(&bytes).unwrap(); + // assert_eq!(msg1, msg2); + // assert_eq!(msg2, message); + } +} + +pub fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("ros_deserialization", |b| b.iter(|| bench_ros_deserialization())); + c.bench_function("cdr_deserialization", |b| b.iter(|| bench_cdr_deserialization())); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches);