From 8c5aec02c421c9aa7dba8c3e4aca58d02b3d322f Mon Sep 17 00:00:00 2001 From: Jordan Pittman Date: Sat, 12 Oct 2024 18:36:00 -0400 Subject: [PATCH] add: Throughput testing helpers --- crates/core/src/util/mod.rs | 4 +++ crates/core/src/util/throughput.rs | 47 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 crates/core/src/util/throughput.rs diff --git a/crates/core/src/util/mod.rs b/crates/core/src/util/mod.rs index 085d04c3b..82934ee25 100644 --- a/crates/core/src/util/mod.rs +++ b/crates/core/src/util/mod.rs @@ -2,6 +2,7 @@ mod escape; mod fast_stack; mod gurantee; mod segment; +mod throughput; #[allow(unused_imports)] pub use crate::util::escape::*; @@ -14,3 +15,6 @@ pub use crate::util::gurantee::*; #[allow(unused_imports)] pub use crate::util::segment::*; + +#[allow(unused_imports)] +pub use crate::util::throughput::*; diff --git a/crates/core/src/util/throughput.rs b/crates/core/src/util/throughput.rs new file mode 100644 index 000000000..17dcda8f4 --- /dev/null +++ b/crates/core/src/util/throughput.rs @@ -0,0 +1,47 @@ +use std::fmt::Display; + +pub struct Throughput { + rate: f64, + elapsed: std::time::Duration, +} + +impl Display for Throughput { + #[inline(always)] + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{}/s over {:.2}s", format_byte_size(self.rate), self.elapsed.as_secs_f64()) + } +} + +impl Throughput { + #[inline(always)] + pub fn compute(iterations: usize, memory_baseline: usize, cb: F) -> Self + where + F: Fn(), + { + let now = std::time::Instant::now(); + for _ in 0..iterations { + cb(); + } + let elapsed = now.elapsed(); + let memory_size = iterations * memory_baseline; + + Self { + rate: memory_size as f64 / elapsed.as_secs_f64(), + elapsed, + } + } +} + +#[inline(always)] +fn format_byte_size(size: f64) -> String { + let units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; + let unit = 1000; + let mut size = size; + let mut i = 0; + while size > unit as f64 { + size /= unit as f64; + i += 1; + } + + format!("{:.2} {}", size, units[i]) +}