Hacker News new | ask | show | jobs
by mg 1459 days ago
Yay, let's talk about FizzBuzz!

This is the fastest PHP version I could come up with so far:

    <?php
    
    ob_start(null, 32000);
    
    $a = [0, 1, 'fizz', 3, 'buzz', 'fizz',
          6, 7, 'fizz', 'buzz', 10, 'fizz',
          12, 13, 'fizzbuzz', ''];
    
    for ($i = 1; $i < PHP_INT_MAX-15; $i+=15) {
        $a[0] = $i;
        $a[1] = $i+1;
        $a[3] = $i+3;
        $a[6] = $i+6;
        $a[7] = $i+7;
        $a[10] = $i+10;
        $a[12] = $i+12;
        $a[13] = $i+13;
        echo join("\n", $a);
    }
I'm sure there still are ways to make it faster. But I fail to think of them. Except for unrolling multiple loops into one. But that is so ugly. Any ideas of elegant ways to make it faster?

Testing the performance like this:

    php fizzbuzz.php | pv > /dev/null
215MiB/s on my slowish laptop.

The "yes" command gives me about 10x the throughoutput:

    yes fizz | pv > /dev/null
3.04GiB/s

Shows how much wiggle room there still is!

I also wrote a python version of it, but it performs 10x slower:

    a = [0, 1, 'fizz', 3, 'buzz', 'fizz',
         6, 7, 'fizz', 'buzz', 10, 'fizz',
         12, 13, 'fizzbuzz'];

    for i in range(1,1000000000,15):
        a[0] = i;
        a[1] = i+1;
        a[3] = i+3;
        a[6] = i+6;
        a[7] = i+7;
        a[10] = i+10;
        a[12] = i+12;
        a[13] = i+13;
        print("\n".join([str(x) for x in a]));
Maybe the bottleneck is the loop that converts the integers to strings? Maybe someone with Python knowledge can comment on how to approach this in Python!
2 comments

https://tech.marksblogg.com/fastest-fizz-buzz.html

Not sure I'd call writing Assembly "elegant" but hey!

Yeah, I know all the different language versions from the FizzBuzz shootout on Stackoverflow.

I'm particularly interested in comparing PHP, Python and Javascript.

So I would like to write an "optimal" PHP version first. Afaik that has not been done yet.

Probably your implementation is limited by the speed PHP/echo can output things to stdout, rather than your implementation per-se.

Better, use a benchmarking framework/library to see how many OP/sec you can do, within the PHP runtime, so you remove stdout from the benchmark.

Well, that's part of the challenge. To write to stdout as fast as possible.

There is a large FizzBuzz shootout here that I like:

https://codegolf.stackexchange.com/questions/215216

I think it's a nice "standard" for FizzBuzz comparison.

Well, then remove the whole "fizzbuzz" part of the equation and just try to output as much data to stdout as possible.

Conflating the two seems to confuse more than measure anything useful.