// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Measures the wire layer on representative message shapes. //! //! Run through the build system: `zig build bench -Doptimize=ReleaseFast`. //! Each case is measured three ways: `encode` builds the body with an //! `Encoder` and serializes the complete message, `parse` is `parseMessage`, //! which validates the header and walks the whole body against its //! signature, and `read` is a typed `Decoder` pass over the body, which is //! what an application does after parsing. Encode is the full cost of //! producing a message, parse plus read the full cost of consuming one. //! //! This imports `wire` rather than the public module because it measures the //! wire layer by itself; `parseMessage` and `encodeMessage` are internals //! that `Connection` drives. const std = @import("std"); const Io = std.Io; const wire = @import("wire"); const Decoder = wire.Decoder; const Encoder = wire.Encoder; /// Every timed loop runs at least this long, so a fast case is measured over /// many iterations rather than trusting one clock read. const min_ns_per_case: i96 = 500 * std.time.ns_per_ms; /// One message shape: a body builder, the signature describing what it /// builds, and the typed read pass that consumes it. The builder writes only /// constant values, so a timed encode measures the encoder rather than the /// formatting of test data. const Case = struct { name: []const u8, signature: []const u8, fill: *const fn (body: *Encoder) anyerror!void, read: *const fn (decoder: *Decoder) anyerror!void, }; const EncodeContext = struct { allocator: std.mem.Allocator, case: *const Case, }; const ParseContext = struct { allocator: std.mem.Allocator, data: []u8, }; const ReadContext = struct { message: *const wire.Message, read: *const fn (decoder: *Decoder) anyerror!void, }; fn nowNs(io: Io) i96 { return Io.Clock.Timestamp.now(io, .awake).raw.nanoseconds; } /// Run `f` repeatedly until `min_ns_per_case` has elapsed, returning the mean /// nanoseconds per call. fn measure(io: Io, context: anytype, comptime f: fn (@TypeOf(context)) anyerror!void) !f64 { // A short warmup so the first iteration's cache misses are not averaged in. for (0..16) |_| try f(context); var iterations: usize = 0; const start = nowNs(io); var elapsed: i96 = 0; while (elapsed < min_ns_per_case) { for (0..64) |_| try f(context); iterations += 64; elapsed = nowNs(io) - start; } return @as(f64, @floatFromInt(elapsed)) / @as(f64, @floatFromInt(iterations)); } fn mbPerSecond(bytes_per_call: usize, ns_per_call: f64) f64 { return (@as(f64, @floatFromInt(bytes_per_call)) / (1024.0 * 1024.0)) / (ns_per_call / @as(f64, std.time.ns_per_s)); } /// Encode one complete message around `body`, in the shape of a signal so no /// reply bookkeeping is involved. fn buildMessage(allocator: std.mem.Allocator, signature: []const u8, body: []const u8) ![]u8 { return wire.encodeMessage(allocator, .{ .message_type = .signal, .path = "/org/example/Bench", .interface = "org.example.Bench", .member = "Case", .signature = signature, }, 1, body, 0); } /// The whole encode side: build the body, serialize the message around it, /// release both. The allocator is part of the measurement because it is part /// of encoding a real message. fn encodeOnce(context: EncodeContext) anyerror!void { var body: Encoder = .init(context.allocator); defer body.deinit(); try context.case.fill(&body); const data = try buildMessage(context.allocator, context.case.signature, body.bytes()); std.mem.doNotOptimizeAway(data.ptr); context.allocator.free(data); } /// `parseMessage` takes ownership of its arguments, but only `deinit` releases /// them, so parsing the same buffer repeatedly without deiniting the result is /// safe and keeps the allocator out of the measurement. fn parseOnce(context: ParseContext) anyerror!void { var no_fds = [_]std.posix.fd_t{}; const message = try wire.parseMessage(context.allocator, context.data, &no_fds); std.mem.doNotOptimizeAway(&message); } fn readOnce(context: ReadContext) anyerror!void { var decoder = context.message.bodyDecoder(); try context.read(&decoder); try decoder.end(); } fn fillSmall(body: *Encoder) anyerror!void { try body.string("Hello, benchmark!"); } fn readSmall(d: *Decoder) anyerror!void { std.mem.doNotOptimizeAway(try d.string()); } /// The shape of a `ListNames` reply: an array of several hundred short /// strings, all of which must be UTF-8 validated. fn fillNames(body: *Encoder) anyerror!void { const array = try body.beginArray('s'); for (0..500) |_| try body.string("org.freedesktop.Service00"); try body.endArray(array); } fn readNames(d: *Decoder) anyerror!void { const end = try d.beginArray('s'); while (!try d.arrayFinished(end)) { std.mem.doNotOptimizeAway(try d.string()); } try d.endArray(end); } /// The same shape with lightly accented strings: mostly ASCII with a couple /// of two-byte sequences each, the realistic non-ASCII case, which drops the /// text validation out of its vector loop at the first accent. fn fillAccented(body: *Encoder) anyerror!void { const array = try body.beginArray('s'); for (0..500) |_| try body.string("org.freedesktop.S\u{e9}rvic\u{e9}00"); try body.endArray(array); } /// The same shape again with fully multibyte strings, where the vector loop /// never gets to run at all: every character is a three-byte sequence. fn fillCjk(body: *Encoder) anyerror!void { const array = try body.beginArray('s'); for (0..500) |_| try body.string("\u{65e5}\u{672c}\u{8a9e}\u{306e}\u{30b5}\u{30fc}\u{30d3}\u{30b9}00"); try body.endArray(array); } /// The shape of a `GetManagedObjects`-style listing: an array of object /// paths, each validated against the path syntax. fn fillPaths(body: *Encoder) anyerror!void { const array = try body.beginArray('o'); for (0..500) |_| try body.objectPath("/org/freedesktop/Service00/device00/port00"); try body.endArray(array); } fn readPaths(d: *Decoder) anyerror!void { const end = try d.beginArray('o'); while (!try d.arrayFinished(end)) { std.mem.doNotOptimizeAway(try d.objectPath()); } try d.endArray(end); } /// An array of signatures, each validated against the signature grammar, /// which no other case exercises beyond the short ones on variants. fn fillSignatures(body: *Encoder) anyerror!void { const array = try body.beginArray('g'); for (0..500) |_| try body.signature("aa{s(iiu)}"); try body.endArray(array); } fn readSignatures(d: *Decoder) anyerror!void { const end = try d.beginArray('g'); while (!try d.arrayFinished(end)) { std.mem.doNotOptimizeAway(try d.signature()); } try d.endArray(end); } /// One large string, where text validation itself is the whole cost and none /// of it is hidden by per-string overhead. The content is fully multibyte, /// which is the validator's worst case. fn fillBigText(body: *Encoder) anyerror!void { try body.string(std.mem.asBytes(&big_text_storage)); } var big_text_storage: [999_999]u8 = undefined; fn readBigText(d: *Decoder) anyerror!void { std.mem.doNotOptimizeAway((try d.string()).ptr); } /// The shape of a `GetAll` properties reply: string keys to mixed variants. fn fillProperties(body: *Encoder) anyerror!void { const array = try body.beginArray('{'); for (0..100) |i| { try body.dictEntryAlignment(); try body.string("Property00"); switch (i % 4) { 0 => { try body.variantSignature("u"); try body.uint32(@intCast(i)); }, 1 => { try body.variantSignature("s"); try body.string("a string property value"); }, 2 => { try body.variantSignature("t"); try body.uint64(i); }, else => { try body.variantSignature("d"); try body.double(@floatFromInt(i)); }, } } try body.endArray(array); } fn readProperties(d: *Decoder) anyerror!void { const end = try d.beginArray('{'); while (!try d.arrayFinished(end)) { try d.structAlignment(); std.mem.doNotOptimizeAway(try d.string()); const signature = try d.variantSignature(); switch (signature[0]) { 'u' => std.mem.doNotOptimizeAway(try d.uint32()), 's' => std.mem.doNotOptimizeAway(try d.string()), 't' => std.mem.doNotOptimizeAway(try d.uint64()), 'd' => std.mem.doNotOptimizeAway(try d.double()), else => return error.InvalidSignature, } } try d.endArray(end); } /// A large array of a fixed-size type, where per-element overhead dominates. fn fillIntegers(body: *Encoder) anyerror!void { const array = try body.beginArray('i'); for (0..100_000) |i| try body.int32(@intCast(i % 1000)); try body.endArray(array); } fn readIntegers(d: *Decoder) anyerror!void { const end = try d.beginArray('i'); while (!try d.arrayFinished(end)) { std.mem.doNotOptimizeAway(try d.int32()); } try d.endArray(end); } /// The same hundred thousand integers through the bulk `int32Slice` pair, /// which on a little-endian host is a copy in each direction. var int_storage: [100_000]i32 = undefined; fn fillIntegersBulk(body: *Encoder) anyerror!void { const array = try body.beginArray('i'); try body.int32Slice(&int_storage); try body.endArray(array); } fn readIntegersBulk(d: *Decoder) anyerror!void { const end = try d.beginArray('i'); std.mem.doNotOptimizeAway((try d.int32Slice(end, &int_storage)).ptr); try d.endArray(end); } /// A megabyte of `ay`, the worst case for byte-at-a-time element loops. fn fillBytes(body: *Encoder) anyerror!void { const array = try body.beginArray('y'); for (0..1024 * 1024) |i| try body.byte(@truncate(i)); try body.endArray(array); } fn readBytes(d: *Decoder) anyerror!void { const end = try d.beginArray('y'); while (!try d.arrayFinished(end)) { std.mem.doNotOptimizeAway(try d.byte()); } try d.endArray(end); } /// The same megabyte through the bulk `byteSlice` pair, which is what an /// application moving binary payloads should be using. var bulk_storage: [1024 * 1024]u8 = undefined; fn fillBulk(body: *Encoder) anyerror!void { const array = try body.beginArray('y'); try body.byteSlice(&bulk_storage); try body.endArray(array); } fn readBulk(d: *Decoder) anyerror!void { const end = try d.beginArray('y'); std.mem.doNotOptimizeAway((try d.byteSlice(end)).ptr); try d.endArray(end); } /// An array of structs, which realigns to an 8 boundary per element. fn fillStructs(body: *Encoder) anyerror!void { const array = try body.beginArray('('); for (0..10_000) |i| { try body.structAlignment(); try body.uint32(@intCast(i % 1000)); try body.string("element"); } try body.endArray(array); } fn readStructs(d: *Decoder) anyerror!void { const end = try d.beginArray('('); while (!try d.arrayFinished(end)) { try d.structAlignment(); std.mem.doNotOptimizeAway(try d.uint32()); std.mem.doNotOptimizeAway(try d.string()); } try d.endArray(end); } pub fn main(init: std.process.Init) !void { const allocator = init.gpa; const io = init.io; for (&bulk_storage, 0..) |*b, i| b.* = @truncate(i); for (&int_storage, 0..) |*v, i| v.* = @intCast(i % 1000); // 333,333 copies of a three-byte sequence fill the buffer exactly. for (0..big_text_storage.len / 3) |i| { @memcpy(big_text_storage[i * 3 ..][0..3], "\u{65e5}"); } var stdout_buffer: [4096]u8 = undefined; var stdout_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_writer.interface; const cases = [_]Case{ .{ .name = "small string reply", .signature = "s", .fill = fillSmall, .read = readSmall }, .{ .name = "500 bus names (as)", .signature = "as", .fill = fillNames, .read = readNames }, .{ .name = "500 accented names (as)", .signature = "as", .fill = fillAccented, .read = readNames }, .{ .name = "500 CJK names (as)", .signature = "as", .fill = fillCjk, .read = readNames }, .{ .name = "500 object paths (ao)", .signature = "ao", .fill = fillPaths, .read = readPaths }, .{ .name = "500 signatures (ag)", .signature = "ag", .fill = fillSignatures, .read = readSignatures }, .{ .name = "1 MB CJK text (s)", .signature = "s", .fill = fillBigText, .read = readBigText }, .{ .name = "100 properties (a{sv})", .signature = "a{sv}", .fill = fillProperties, .read = readProperties }, .{ .name = "100k int32 (ai)", .signature = "ai", .fill = fillIntegers, .read = readIntegers }, .{ .name = "100k int32 bulk (ai)", .signature = "ai", .fill = fillIntegersBulk, .read = readIntegersBulk }, .{ .name = "1 MiB bytes (ay)", .signature = "ay", .fill = fillBytes, .read = readBytes }, .{ .name = "1 MiB bulk (ay)", .signature = "ay", .fill = fillBulk, .read = readBulk }, .{ .name = "10k structs (a(us))", .signature = "a(us)", .fill = fillStructs, .read = readStructs }, }; try stdout.print("{s:<24} {s:>9} {s:>14} {s:>9} {s:>13} {s:>9} {s:>12} {s:>9}\n", .{ "case", "bytes", "encode ns/msg", "MB/s", "parse ns/msg", "MB/s", "read ns/msg", "MB/s", }); for (&cases) |*case| { var body: Encoder = .init(allocator); defer body.deinit(); try case.fill(&body); const data = try buildMessage(allocator, case.signature, body.bytes()); var no_fds = [_]std.posix.fd_t{}; var message = try wire.parseMessage(allocator, data, &no_fds); const encode_ns = try measure(io, EncodeContext{ .allocator = allocator, .case = case }, encodeOnce); const parse_ns = try measure(io, ParseContext{ .allocator = allocator, .data = data }, parseOnce); const read_ns = try measure(io, ReadContext{ .message = &message, .read = case.read }, readOnce); try stdout.print("{s:<24} {d:>9} {d:>14.1} {d:>9.1} {d:>13.1} {d:>9.1} {d:>12.1} {d:>9.1}\n", .{ case.name, data.len, encode_ns, mbPerSecond(data.len, encode_ns), parse_ns, mbPerSecond(data.len, parse_ns), read_ns, mbPerSecond(data.len, read_ns), }); message.deinit(); } try stdout.flush(); }