From 7ee7530f2f4068c2642136a484e945ffa4b89cee Mon Sep 17 00:00:00 2001 From: Ben Sinclair Date: Tue, 12 Mar 2024 12:35:51 +1100 Subject: [PATCH] Fix formatting for fractions with leading zeroes --- util/format.zig | 18 ++++++++---------- util/format_test.zig | 25 ++++++++++++++++++++----- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/util/format.zig b/util/format.zig index 1d1f3fc..c0c3899 100644 --- a/util/format.zig +++ b/util/format.zig @@ -2,23 +2,21 @@ const std = @import("std"); const Color = @import("./color.zig").Color; const log = std.log.scoped(.zbench_format); -pub fn duration(buffer: []u8, d: u64) ![]u8 { +pub fn duration(buffer: []u8, nanoseconds: u64) ![]u8 { const units = [_][]const u8{ "ns", "µs", "ms", "s" }; - var scaledDuration: u64 = d; + var scaled: f64 = @floatFromInt(nanoseconds); var unitIndex: usize = 0; - var fractionalPart: u64 = 0; - - while (scaledDuration >= 1_000 and unitIndex < units.len - 1) { - fractionalPart = scaledDuration % 1_000; - scaledDuration /= 1_000; + while (scaled >= 1000.0 and unitIndex < units.len - 1) { + scaled /= 1000.0; unitIndex += 1; } - const formatted = try std.fmt.bufPrint(buffer, "{d}.{d}{s}", .{ scaledDuration, fractionalPart, units[unitIndex] }); - - return formatted; + return if (0 < unitIndex) try std.fmt.bufPrint(buffer, "{d:.3}{s}", .{ + scaled, + units[unitIndex], + }) else try std.fmt.bufPrint(buffer, "{d}ns", .{nanoseconds}); } pub fn memorySize(bytes: u64, allocator: std.mem.Allocator) ![]const u8 { diff --git a/util/format_test.zig b/util/format_test.zig index 1fe2257..c39a61c 100644 --- a/util/format_test.zig +++ b/util/format_test.zig @@ -8,27 +8,42 @@ test "duration" { { const result = try format.duration(buffer[0..], 1); - try std.testing.expectEqualSlices(u8, "1.0ns", result); + try std.testing.expectEqualSlices(u8, "1ns", result); } { const result = try format.duration(buffer[0..], 999); - try std.testing.expectEqualSlices(u8, "999.0ns", result); + try std.testing.expectEqualSlices(u8, "999ns", result); } { const result = try format.duration(buffer[0..], 1000); - try std.testing.expectEqualSlices(u8, "1.0µs", result); + try std.testing.expectEqualSlices(u8, "1.000µs", result); } { const result = try format.duration(buffer[0..], 1000000); - try std.testing.expectEqualSlices(u8, "1.0ms", result); + try std.testing.expectEqualSlices(u8, "1.000ms", result); } { const result = try format.duration(buffer[0..], 1000000000); - try std.testing.expectEqualSlices(u8, "1.0s", result); + try std.testing.expectEqualSlices(u8, "1.000s", result); + } + + { + const result = try format.duration(buffer[0..], 1234567890); + try std.testing.expectEqualSlices(u8, "1.235s", result); + } + + { + const result = try format.duration(buffer[0..], 1023456789); + try std.testing.expectEqualSlices(u8, "1.023s", result); + } + + { + const result = try format.duration(buffer[0..], 1999999999); + try std.testing.expectEqualSlices(u8, "2.000s", result); } {