lib/bench/src/jsonl.zig
daab053ee43316e1809a84551d573ddd1e5bf3d2
1 const std = @import("std");
2 const pretty_json = @import("pretty").json;
3
4 const stats_mod = @import("stats/root.zig");
5
6 pub const Unit = struct {
7 name: []const u8,
8 count: u64,
9 };
10
11 pub fn writePerUnitFields(
12 object: pretty_json.Object,
13 value_name: []const u8,
14 value: f64,
15 units: []const Unit,
16 ) !void {
17 for (units) |unit| {
18 try object.fieldParts(
19 &.{ value_name, "_per_", unit.name },
20 stats_mod.valuePerUnit(value, unit.count),
21 );
22 }
23 }
24
25 pub fn writeNamedPerUnitFields(
26 object: pretty_json.Object,
27 name: []const u8,
28 value_name: []const u8,
29 value: f64,
30 units: []const Unit,
31 ) !void {
32 for (units) |unit| {
33 try object.fieldParts(
34 &.{ name, "_", value_name, "_per_", unit.name },
35 stats_mod.valuePerUnit(value, unit.count),
36 );
37 }
38 }
39
40 pub fn writeMemoryCounts(
41 object: pretty_json.Object,
42 name: []const u8,
43 counts: anytype,
44 units: []const Unit,
45 ) !void {
46 try object.fieldParts(&.{ name, "_alloc_count" }, counts.alloc_count);
47 try object.fieldParts(&.{ name, "_free_count" }, counts.free_count);
48 try object.fieldParts(&.{ name, "_alloc_bytes" }, counts.alloc_bytes);
49 try writeNamedPerUnitFields(
50 object,
51 name,
52 "alloc_bytes",
53 @floatFromInt(counts.alloc_bytes),
54 units,
55 );
56 }
57
58 test "write per-unit fields" {
59 var out = std.Io.Writer.Allocating.init(std.testing.allocator);
60 defer out.deinit();
61
62 const units = [_]Unit{
63 .{ .name = "source_op", .count = 4 },
64 .{ .name = "final_op", .count = 8 },
65 };
66 var stream = pretty_json.Writer.init(&out.writer, .minified);
67 const object = try stream.object();
68 try writePerUnitFields(object, "ns", 120, &units);
69 try object.end();
70
71 const text = out.written();
72 try std.testing.expectEqualStrings(
73 "{\"ns_per_source_op\":30,\"ns_per_final_op\":15}",
74 text,
75 );
76 }
77
78 test "write named memory count fields" {
79 var out = std.Io.Writer.Allocating.init(std.testing.allocator);
80 defer out.deinit();
81
82 const units = [_]Unit{.{ .name = "source_op", .count = 8 }};
83 var stream = pretty_json.Writer.init(&out.writer, .minified);
84 const object = try stream.object();
85 try writeMemoryCounts(
86 object,
87 "phase",
88 .{ .alloc_count = 3, .free_count = 2, .alloc_bytes = @as(u64, 64) },
89 &units,
90 );
91 try object.end();
92
93 const text = out.written();
94 try std.testing.expectEqualStrings(
95 "{\"phase_alloc_count\":3,\"phase_free_count\":2," ++
96 "\"phase_alloc_bytes\":64,\"phase_alloc_bytes_per_source_op\":8}",
97 text,
98 );
99 }