by sillysaurusx · 5y ago · 0 comments
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...
For comparison, that time is on par with integer multiplication.
All I mean is that I appreciate the author making their thought process accessible. It certainly looks like virtuosity, but I'm not competent enough to judge.
// 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.
If you show a modern compiler the typical idiomatic blob of code for counting the set bits in a word in a language like C, the compiler goes "Oh, popcount I know this" and when targeting modern CPUs it emits a single instruction, the popcount instruction for that CPU.
In APL idiom recognition was essential to making even a halfway decent compiler. It's easy, and idiomatic, to write APL which would be tremendously wasteful if implemented naively, while recognising common idioms could remove lots of that waste without needing the level of sophistication modern compilers have during optimisation.
Because the compiler knows about idioms you should not try to optimise your programs by writing non-idiomatic code until you've determined you have a performance problem and the non-idiomatic code is identified as a way to fix it. Otherwise it may be that the compiler improves and now your code is not only harder to maintain it also has worse performance than the idiomatic solution.
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.
If it were, you'd claim the prize. If you really want to hurt a troll, wouldn't you try to separate them from their $500?
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
Measured over 10 s after a 10 s burn-in period, Julia 1.7 on Ubuntu 21.10.
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...