Sanely optimized fizzbuzz
Brian Callahan
bcallah at openbsd.org
Sat Oct 30 07:30:26 UTC 2021
On Saturday, 30 October 2021 at 05:31:48 UTC, monkyyy wrote:
> https://codegolf.stackexchange.com/questions/215216/high-throughput-fizz-buzz/236630#236630
>
> So this was bought up on the discord and it seems interesting,
> so how about a little contest?
>
> Speed up fizzbuzz but let's do it a bit sanely:
>
> Some rough rules:
>
> * Less then 100 lines of code
> * Let's not define your own asm marco language like the winning
> result
> * Use d
On my very slow machine, the naive solution in C that you linked
to runs at around 64.5 MB/s.
An equally naive version in D runs on the same machine at around
920 MB/s:
```d
import std.stdio;
import std.conv;
string fizzbuzz()
{
string str;
for (int i = 1; i <= 15000; i++) {
if (i % 15 == 0)
str ~= "FizzBuzz\n";
else if (i % 3 == 0)
str ~= "Fizz\n";
else if (i % 5 == 0)
str ~= "Buzz\n";
else
str ~= to!string(i) ~ "\n";
}
return str;
}
void main()
{
string fb = fizzbuzz();
for (int i = 0; i < 1000000; i++)
write(fb);
}
```
You could do CTFE by turning `string fb = fizzbuzz();` into
`static string fb = fizzbuzz();` but I found that reduces runtime
performance to about 901 MB/s on my machine.
More information about the Digitalmars-d
mailing list