Hacker News new | ask | show | jobs
by AndyKelley 2721 days ago
Zig:

    const std = @import("std");

    pub fn main() u8 {
        @setEvalBranchQuota(2000);
        const precomputed_output = comptime fizzbuzz: {
            var s: []const u8 = "";
            var i: usize = 1;
            while (i <= 100) : (i += 1) {
                if (i % 3 == 0 and i % 5 == 0) {
                    s = s ++ "FizzBuzz\n";
                } else if (i % 3 == 0) {
                    s = s ++ "Fizz\n";
                } else if (i % 5 == 0) {
                    s = s ++ "Buzz\n";
                } else {
                    var buf: [20]u8 = undefined;
                    const n = buf[0..std.fmt.formatIntBuf(&buf, i, 10, false, 0)];
                    s = s ++ n ++ "\n";
                }
            }
            break :fizzbuzz s;
        };
        const stdout = std.io.getStdOut() catch return 1;
        stdout.write(precomputed_output) catch return 1;
        return 0;
    }
Output:

    $ zig build-exe fizzbuzz.zig
    $ ./fizzbuzz
    <correct output>
    $ strace ./fizzbuzz
    execve("./fizzbuzz", ["./fizzbuzz"], 0x7ffeeb1a4540 /* 132 vars */) = 0
    write(1, "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBu"..., 4131
    exit(0)                                 = ?
The entire program is 1 write syscall that outputs the answer. I don't think it's theoretically possible to get faster than that.
1 comments

> The entire program is 1 write syscall that outputs the answer. I don't think it's theoretically possible to get faster than that.

If stdout happens to be a socket, setsockopt + SO_SNDBUF might help runtime. But that is an extremely byzantine scenario. Another consideration might be a fast CPU attached to a fast but tiny icache and dcache with very slow memory, where reading the pregenerated string is slower than computing it.