261 points · by Croftengea · 4y ago · 159 comments
55 GiB/s FizzBuzz - https://news.ycombinator.com/item?id=29031488 - Oct 2021 (255 comments)
Alex Smith [1] is also known for winning the Wolfram 2,3 Turing Machine Research Prize [2].
[1] https://www.cs.bham.ac.uk/~ais523/
[2] https://writings.stephenwolfram.com/2007/10/the-prize-is-won...
All of the top contenders on https://codegolf.stackexchange.com/questions/215216/high-thr... do exactly this.
Yes there is a lot of optimization specific to languages, OS, CPU... but the takeaway for me isn't that you have to go that extent to build an order of magnitude improvement, you can still achieve many order of magnitudes of improvement by understanding what is happening when you use something like the modulo function and that if you have requirements where you can avoid using it then that's the win.
For FizzBuzz you are told it "iterates from 1 to <some number>"... and modulo would be perfect for "take a single number and produce Fizz, Buzz or FizzBuzz if it's divisable by 3, 5, or both 3 and 5"... but as we're iterating, counters are better suited to the task.
I love seeing epic code golf (and the solution outlined in the article is it), but the takeaway for the majority of engineers is that significant improvements can be made with a readable and maintainable solution just by understanding the requirements and comp sci fundamentals.
The record-beating versions all do something clever to optimise the printing of the numbers between the "Fizz" and "Buzz" strings.
AVX2 is not SSE2 - SSE2 is much, much older.
You want to check for the avx2 flag itself.
Even the unoptimized C version is 10x slower than the one that is painstakingly optimized.
Some of this performance gain will certain be achievable by ML/AI assisted compilers and translators. In that case, even a 2x speedup would be game changing. Is anyone using ML in compilers yet? The part where you verify the code still does what you wanted it to do seems trickiest.
Yes :)
Check out TVM for something mainstream: http://tvm.apache.org/
And LibNC for something esoteric (but elegant): https://bellard.org/libnc/
It was more about things like http://compilerai.apps.iitd.ac.in/
In this case, though, the biggest differences aren't coming from C vs assembler but from walking away from platform conventions -- ABI, memory layout, CPU compatibility. It might be easier to write assembly than to teach the compiler how to generate code that does this, but that's largely because you don't need these optimisations in most cases. If the methods used provided a general speedup, it would be worth implementing them in compilers.
And yet, that is one of the optimizations that helps get this one the speed crown.
And from the looks of it, at least 100x is possible. It's a shame therefore that even a 1% performance increase in a compiler release is considered pretty noteworthy.
I stopped once I could do it in simple code with no math except addition, 15 numbers at a time.
for (int x = 0 ; x < 1000000 ; x+= 15) {
printf("%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n",
1 + x, 2 + x, 4 + x, 7 + x, 8 + x, 11 + x, 13 + x, 14 + x);
}
That is simple enough and fast enough for me.for (i=1;i<n;i+=15) { print i; print i+1; print 'fizz' print i+3 ... } You have the fastest , dont you? (if the ending n is important then one can just write 15 of such loops/endgame depending on the modulus). Since there is no 'if' the branch predictor should be on your side.
“fizz” % 3, “buzz” % 5, what is the % 15 for?
You can blow a interviewee’s mind by saying, great, now “bang” % 7… and (hopefully!) watch the light dawn.
// why so serious? :-)
It's true that you could do this with something like:
result = ''
if x % 3 == 0: result += 'fizz'
if x % 5 == 0: result += 'buzz'
if result == '': result += str(x)
return result
to append fizz when for 15 and also continue processing and append buzz, but this requires an extra comparison to check that you did neither of those to print the number.but note that if you do 3 comparisons, or 2 comparisons and an "extra" comparison, you've done the same number of comparisons, it's not really 'extra'
then go ahead and keep adding factors and see which results in more comparisons as we rack up the actually extra comparisons for various combinations of factors
btw and ftw, your modulo and string test example, more correct than the usual implementation, is among the most efficient:
http://www.zoharbabin.com/which-fizzbuzz-solution-is-the-mos...
// still not so serious...
This does not mean 102.4 GBps is achievable on a single core, but if L2 bandwidth is the limiting factor it very well could be.
[1] https://dougallj.github.io/applecpu/firestorm.html [2] https://www.anandtech.com/show/17024/apple-m1-max-performanc...
Interesting, but not very practical.
This makes me happy. The order is exactly as it should be, much to the disappointment of the Rustaceans.
It's a nice reminder that for the ultimate performance, there is no substitute for knowing exactly what the assembler is doing.
It's also a nice reminder that most of us will never want to do that.
EDIT: Whoa. It's late, and I thought Rust was at 30 GB/s instead of 3, i.e. roughly neck and neck with C. I meant to make a good-natured joke. There must be something wrong with the Rust implementation to be 10x slower; I wonder what it is.
As I mentioned further down in the comments, I'll donate $500 to Watsi if someone manages to displace the C implementation in Rust or any other language besides C/C++/ASM. Be sure to DM me on Twitter (https://twitter.com/theshawwn) if you do, both so I'll see it and so that I can congratulate you. I'm sure it's possible, but it's sort of interesting that the activation energy is so high.
> It's a nice reminder that for the ultimate performance, there is no substitute for knowing exactly what the assembler is doing.
C and C++ do not let you know exactly what the assembler is doing. I work on compilers for a living and despite that--perhaps because of that--I have no confidence that I can predict what instructions the compiler will generate ahead of time. If I need to know the actual instructions, I run my code through Godbolt and check. C, C++, and Rust are all millions of lines of LLVM optimization passes away from the metal.
Based on some other comments, I suspect that all the time is being spent in locking stdout, which you can amortize by using Stdout::lock [1]. As is so often the case when microbenchmarks are discussed online, this has nothing to do with the language.
Also, it shouldn't need to be said, but FizzBuzz is so totally unrepresentative of real workloads that you shouldn't draw any conclusions about language performance from it.
[1]: https://doc.rust-lang.org/stable/std/io/struct.Stdout.html#m...
You most certainly can’t unless your code is unsafe and in that case the comparison isn’t so interesting anymore.
Also the third entry is not the one in Rust. It's just that the Rust entry came later and thus was not included in the plot. The third entry is https://codegolf.stackexchange.com/a/215236/56694; it is also C.
> displace the C implementation in Rust or any other language besides C/C++/ASM
This is not a language contest, it's an algorithmic contest: that is, it's the best algorithm that wins, not the best compiler. The top entry, converted into C or Rust by mostly menial work, would probably be only a few % slower and would displace the C implementation.
If so that makes me a bit sad, because in the modern day we'd want to assume that compilers have gotten a little better at optimization.
Seriously. It's eye-popping. It's eldritch madness. It's black wizardry. The blackest of the black arts.
The "fastest FizzBuzz" implementation isn't merely "fast". It's faster than memcpy()!!!
Expecting compilers to outperform this tour-de-force is asking a tad too much from compiler writers...
// The bytecode generation loop is unrolled to depth 30, allowing the
// units digits to be hardcoded. The tens digit is stored in %al, and
// incremented every ten lines of output. The parity of the hundreds
// digit is stored in %ymm2: one half predicts the hundreds digit to
// be even, the other to be odd, and the halves are swapped every time
// the tens digit carries (ensuring the predictions are correct).Again: you're comparing the performance of different algorithms. A compiler won't turn bubblesort into quicksort.
Also, why is the ASM version so much faster if the glue code doesn't make much difference? I suppose it matters at the margins...
The remark on the glue code only applies to my entry (the second). The assembly entry uses a completely different (and much more complicated) algorithm than the C entry.
(To check, I wrote a Go program that doen nothing else than fmt.Print($largebody) in a for loop and it tops out at around 10GB/s)
* "asks the Kernel to defragment the physical memory it's using via the madvise system call" * "use 2 MB of RAM each even though neither need 2 MB. This keeps the page table orderly" * "Most competing FizzBuzz implementations call the write system call which can lead to data needing to be copied between user and Kernel space. So vmsplice is used instead."
And then the most fascinating bit: "The CPU's L2 cache is split into two halves, one for calculating the output of FizzBuzz, the other storing the result of the last calculation batch. This means there is no need to use any slower L3 memory operations."
"Slower L3 memory operations", I've not read that sentence before :D
It is really fascinating, but I disagree a bit with your pick :)
To me, the most fascinating part is using a bytecode interpreter. It makes perfect sense, it's basically optimizing the code size to fits in the cache. It's also a bit like defining a whole new instruction set dedicated and optimized for Fizzbuzz!
I think the approach was a bit similar to a VLIW https://en.wikipedia.org/wiki/Very_long_instruction_word where a single 32 bits word is loaded and interpreted at a time.
Most of the state of the Fizzbuzz program is encoded in this bytecode.
> "Slower L3 memory operations", I've not read that sentence before
You hear it all the time when trying to optimize for speed in a hot loop. Keep your data structures in a way that fits in the cache. Align your data with cache boundaries. Code needs to be small too, hence the bytecode approach. This is also the reason why you can't unroll loops too much.
If your implementation does not need to fetch (or write) data from(/to) higher levels of the memory hierarchy, you'll see tremendous gains. There's even this bit in the original source: "while waiting for writes to go through to the L2 cache" :)
There are a few more very interesting hacks, such as the "high-decimal" format that skips the "need to do binary/decimal conversions."
I don't see any reason why the same thing [1] could not be implemented in Rust.
EDIT: I got caught by an off-by-one there, the second fastest solution (doing JIT compilation) is actually [2].
I just enjoy dosing the Rusties with reality every so often.
If you write a Rust version that can beat the C version, I'll donate $500 to Watsi. Good luck!
Aka troll.
I'm using Rust and I'm not dissappointed. Why should I?
But I do appreciate how you create imaginary people in your head, troll them and mentally pad yourself for doing so.
I guess they're just going to have to settle with rust being the best language to write safety-critical high performance concurrent low-level code.
Why it makes you happy? it's a reminder how much we're losing performance, energy and stuff when we're writing in safe/expressive/easy to use languages like Java, C#, Python yada yada
I would guess it's the println! macro eating the time.
In my machine the naive C implementation achieves 81.7 MiB/s, whereas a naive Rust implementation with println achieves 7.58 MiB/s.
When I acquired the stdout's lock once and use writeln!(&mut stdout, ...) instead of println, I got 8.15 MiB/s.
When I wrapped stdout with BufWriter, I got 299 MiB/s.
use std::io::{BufWriter, Write};
fn main() {
let stdout = std::io::stdout();
let stdout = stdout.lock();
let mut stdout = BufWriter::with_capacity(32 * 1024, stdout);
for i in 1..1_000_000_000 {
let _ = match (i % 3 == 0, i % 5 == 0) {
(true, true) => writeln!(&mut stdout, "FizzBuzz"),
(true, false) => writeln!(&mut stdout, "Fizz"),
(false, true) => writeln!(&mut stdout, "Buzz"),
(false, false) => writeln!(&mut stdout, "{}", i),
};
}
}Calling stdout.lock() by itself makes little difference for me. Using BufWriter as you have I get ~80 MiB/s (slightly ahead of PyPy).
My implementation also has/had a String allocation in the loop, kicking that out got me to 120 MiB/s. I tend to write it as though the numbers/strings could be changed by a product manager at any time.
Final edit/errata: I get up to 140 MiB/s by appending .to_string() in the integer case instead of format!(), which makes some sense.
I didn't bother saving my original C implementation, but in retrospect I think I didn't use string concatenation, as I have with other languages. Redoing it with string-concatenation, C is slightly slower than Rust, 110 MiBs. Also makes sense as concatenation in C is slow.
Ruby is slightly slower than Python or Rust, 11 MB/s. I was expecting Python to be slowest among the interpreted languages, apparently not. Pypy yields a speedup to 70 MB/s.
Summing naive implementations (for each i: start with empty string, append fizz/buzz based on the modulus of each, then conditionally append i and print):
Julia 45 KB/s Ruby 11 MB/s CPython 15 MB/s Rust 16 MB/s Pypy 70 MB/s C 160 MB/s
What's it doing to be so much slower? That's shocking. I may not enjoy Rust, but I do respect its ability to approach C++ performance.
Not really. This is a hyper optimised microbenchmark. The actual work being done is so trivial that any "overhead" is really significant and you can get order of magnitude speedups by doing arcane things with caches, eliminating tiny inefficiencies and so on.
Completely off topic, but suddenly all of the crab branding makes a ton more sense
I didn't realize viewing the assembly of a compiled binary was something reserved for C. Someone should tell rust.godbolt.org that it's not supposed to exist.
[1] https://codegolf.stackexchange.com/questions/215216/high-thr...
PS. The Rust implementation is also not very optimal, for example, the stdout is not locked so... what are we even trying to show :-).