Hacker News new | ask | show | jobs
by dacracot 2721 days ago
The next question I like to ask in an interview, once they have fizzbuzz working is, "Now make it more efficient."
4 comments

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.
> 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.

    echo '#include <stdio.h>' > fb.c
    ./fizzbuzz > buf
    xxd -i buf >> fb.c
    echo 'int main(void) { return fwrite(buf, buf_len, 1, stdout) != 1; }' >> fb.c
In time or in (disk | memory) space?