master
 1const std = @import("std");
 2const time = std.time;
 3const unicode = std.unicode;
 4
 5const Timer = time.Timer;
 6
 7const N = 1_000_000;
 8
 9const KiB = 1024;
10const MiB = 1024 * KiB;
11const GiB = 1024 * MiB;
12
13const ResultCount = struct {
14    count: usize,
15    throughput: u64,
16};
17
18fn benchmarkCodepointCount(buf: []const u8) !ResultCount {
19    var timer = try Timer.start();
20
21    const bytes = N * buf.len;
22
23    const start = timer.lap();
24    var i: usize = 0;
25    var r: usize = undefined;
26    while (i < N) : (i += 1) {
27        r = try @call(
28            .never_inline,
29            std.unicode.utf8CountCodepoints,
30            .{buf},
31        );
32    }
33    const end = timer.read();
34
35    const elapsed_s = @as(f64, @floatFromInt(end - start)) / time.ns_per_s;
36    const throughput = @as(u64, @intFromFloat(@as(f64, @floatFromInt(bytes)) / elapsed_s));
37
38    return ResultCount{ .count = r, .throughput = throughput };
39}
40
41pub fn main() !void {
42    // Size of buffer is about size of printed message.
43    var stdout_buffer: [0x100]u8 = undefined;
44    var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
45    const stdout = &stdout_writer.interface;
46
47    try stdout.print("short ASCII strings\n", .{});
48    try stdout.flush();
49    {
50        const result = try benchmarkCodepointCount("abc");
51        try stdout.print("  count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
52    }
53
54    try stdout.print("short Unicode strings\n", .{});
55    try stdout.flush();
56    {
57        const result = try benchmarkCodepointCount("ŌŌŌ");
58        try stdout.print("  count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
59    }
60
61    try stdout.print("pure ASCII strings\n", .{});
62    try stdout.flush();
63    {
64        const result = try benchmarkCodepointCount("hello" ** 16);
65        try stdout.print("  count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
66    }
67
68    try stdout.print("pure Unicode strings\n", .{});
69    try stdout.flush();
70    {
71        const result = try benchmarkCodepointCount("こんにちは" ** 16);
72        try stdout.print("  count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
73    }
74
75    try stdout.print("mixed ASCII/Unicode strings\n", .{});
76    try stdout.flush();
77    {
78        const result = try benchmarkCodepointCount("Hyvää huomenta" ** 16);
79        try stdout.print("  count: {:5} MiB/s [{d}]\n", .{ result.throughput / (1 * MiB), result.count });
80    }
81    try stdout.flush();
82}