From 11142419cd90227dc34667827f5b00f9aba03c70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20M=C3=BCller?= Date: Fri, 21 Jul 2023 11:26:19 -0700 Subject: [PATCH] Include thousands-separators in `bencher` output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As mentioned in #704, the output generated when using the `bencher` output format does not quite match up with that of libtest. One reason being that thousands-separators are not emitted. With this change we adjust the formatting logic for integers (which is only used in `bencher` style reports) to emit thousands-separators, as libtest does. Signed-off-by: Daniel Müller --- src/format.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/format.rs b/src/format.rs index 53c4a4db..d536ab96 100644 --- a/src/format.rs +++ b/src/format.rs @@ -72,8 +72,35 @@ pub fn iter_count(iterations: u64) -> String { } } +/// Format a number with thousands separators. +// Based on the corresponding libtest functionality, see +// https://github.com/rust-lang/rust/blob/557359f92512ca88b62a602ebda291f17a953002/library/test/src/bench.rs#L87-L109 +fn thousands_sep(mut n: u64, sep: char) -> String { + use std::fmt::Write; + let mut output = String::new(); + let mut trailing = false; + for &pow in &[9, 6, 3, 0] { + let base = 10_u64.pow(pow); + if pow == 0 || trailing || n / base != 0 { + if !trailing { + write!(output, "{}", n / base).unwrap(); + } else { + write!(output, "{:03}", n / base).unwrap(); + } + if pow != 0 { + output.push(sep); + } + trailing = true; + } + n %= base; + } + + output +} + +/// Format a value as an integer, including thousands-separators. pub fn integer(n: f64) -> String { - format!("{}", n as u64) + thousands_sep(n as u64, ',') } #[cfg(test)] @@ -101,4 +128,10 @@ mod test { float *= 2.0; } } + + #[test] + fn integer_thousands_sep() { + let n = 140352319.0; + assert_eq!(integer(n), "140,352,319"); + } }