326 points · by homarp · 7y ago · 247 comments
That is, they are compiling C with GCC, but Rust uses LLVM as a backend. Compiling their C code with clang reveals that it is also slightly slower than the C code compiled by GCC, but not faster than Rust.
The actual conclusion here is that the GCC toolchain is slightly faster than the LLVM toolchain for this particular use case, but that isn't really news - it happens all the time.
If one want to focus this on Rust, then the downside of Rust vs C here is that C has a GCC toolchain that happens to be faster for this use case, but Rust does not.
To answer your question: Yes, that particular benchmark was done with GCC and yes, it would have been better to use clang/LLVM for a more fair comparison.
We of course also compared gcc with clang/LLVM and found that clang was 0.8% slower, so it does not explain the difference entirely.
I think it would be quite useful and interesting to figure out why there is still a small difference between clang and Rust. There might be some low hanging fruit in how Rust generates LLVM-IR that could be fixed.
Fun fact: we've a system where Rust is faster than C despite still using more instructions, so yeah, neither instructions nor cycles tell the whole story...
[1] https://people.eecs.berkeley.edu/~apanda/assets/papers/osdi1...
But if that's what this post is comparing, most of the content is probably incorrect, because the main reason C binaries perform better is because the C backend of the C implementation used is better than the Rust backend _for this particular application_. This isn't really news. There are hundreds of benchmarks comparing C and C++ using the GCC and LLVM backends, and each is slightly better than the other, depending on the application. You don't even need to write code in two languages to show this.
The authors appear to be aiming to compare how language differences affect the quality of the generated code. For that, you want to compare two equivalent-quality language frontends using an equivalent-quality optimization pipeline and code-generation backend.
This is, in general, not feasible. But for all languages sharing the same LLVM or GCC backend, doing this comparison is trivial, and would limit the differences to either the frontend implementation, or the language itself.
It makes this statement seem a bit dishonest though:
"Our Rust driver is a few percent slower than our C driver, why? Well, it's of course because of safety features in Rust, but can we quantify that?"
But this was way back in 2016. Numbers from microbenchmarks that old are hardly relevant anymore.
I do wish there were a way to track expectations about integer ranges in a type system, but there currently aren't.
When const generic lands, you will be able to make those assertions! A basic implementation is in nightly.
If one pin points a performance issue due to bound checks, it is also always trivial to disable them in a safe way by writing proper `unsafe` code when it makes a difference.
there are unsafe method for vec that allow you unchecked access to the array, but you need to to write it in unsafe block (some code that is performance sensitive does this).
Passing the smaller reference will be faster in single threaded code. In multi threaded code I'd expect making a thread local copy to be a win, and indeed multi threaded Rust programs tend to be quicker than their C/C++ counterparts.
Yes, this is the "legitimate" criticism to be made here.
I say "legitimate" because LLVM has a bright future and I doubt many people see that as an actual issue.
In general Rust suffers a bit because LLVM is primarily a C++ compiler backend. For example infinite loops without side-effects are UB in C++, but supposed to be well defined in Rust. This is even an issue for C, because `while(1) {}` is a valid in C but UB in C++. https://github.com/rust-lang/rust/issues/28728
Too bad it‘s so broken in LLVM :(
TBF it wasn't just LLVM: in https://github.com/rust-lang/rust/issues/54878 "nikic" and "comex" provided C test cases which failed in both clang[0] and gcc[1]. Though GCC has since fixed the issue while it remains open on LLVM.
Why should Rust beat C? First, it does not suffer from the pointer aliasing faults C has. Second, const really means const, where in C the compiler has to assume any pointer-to-const might be use to write through. Because alias analysis is ironclad, copies can be elided even if some function borrows a reference to the copy.
At a larger scale, improved abstraction tools mean more powerful libraries may be written and used, that would be unavailable to the C coder.
It is routine for C++ programs to be substantially faster than a C program that attempts the same job, even though C++ suffers from the same aliasing flaws C has. In the finance world, you would be laughed out of the room for proposing C for a performance-critical task.
This is why articles about other languages comparing them to some fraction of C performance are amusing. C is a low bar. If you can't beat C, you are Doing It Wrong. In Rust's case, that would be "still doing it wrong"; we may assume fixing this is on the schedule, after various "getting it right" and "compiling faster" goals are met.
That depends on how you write your C++ programs. Virtual functions, runtime type information, STL, RAII ownership can all be performance hits in C++ when compared to C.
Rust has optimization issues of its own apparently.
C isn't a low bar. It is the benchmark.
C isn't the benchmark, assembly is.
C forces you to write code closer to what assembly looks like than Rust or C++. That's good if you can write good assembly, and bad if you cannot. That's particularly bad for writing robust code that doesn't have security vulnerabilities, because the C programmer is required to manually write all checks correctly, while C++ and Rust have abstractions that automatically write the checks for you.
You don't have to use them in those languages if you don't want to.
As I mentioned in the other thread, I think this article is comparing GCC vs LLVM, so the info in the post is kind of moot. But if the authors really believe that Rust bound checks are the culprit of the performance difference, they can just remove them. Takes one line of code, and would show if they are right or wrong.
For example, if a function takes a `std::string` as an argument (by value), any string you pass in will be copied into a new allocation, which will then have to be deallocated. That's fine if the function really needs its own allocation – but it might not. In that case you can avoid the copy by changing the argument type to `const std::string &` or `std::string_view` (the latter being new in C++17)... but the difference is subtle enough that even an experienced programmer might not notice the extraneous copy.
Don't believe me? Consider that in 2014, "std::string was responsible for almost half of all allocations in the Chrome browser process"! [1]
(Rust does a better job here by requiring more explicitness if you want to make expensive copies.)
Oh, there's also an issue where the presence of a destructor pessimizes the calling convention for passing and returning objects of that type by value, but only slightly, and the issue will be addressed in the future. [2]
[1] https://groups.google.com/a/chromium.org/forum/#!msg/chromiu...
[2] https://quuxplusone.github.io/blog/2018/05/02/trivial-abi-10...
Well that's the point: C does not have to do it.
RAII protects you from, e.g., leaking memory. But C can just leak memory, and there isn't really anything substantially wrong with that (you can't get UB from leaking memory).
Checking error values, releasing all resources, doing bound checks, and all the other things that both C++ and Rust do by default are more expensive than doing nothing. Sure, they are zero-cost, in the sense that if you were to write C code that does those, the C code wouldn't be faster. But as mentioned, C code is not required to do these.
With C, you have to manually write the code for doing those things. With C++ and Rust, you have to write the code to opt-out of doing those things (with Rust, removing a bound check is a one liner).
It's a matter of language defaults. I know what the better default for me is.
Similarly, virtual function calls on modern CPUs are essentially free if the branch predictor can predict correctly, the usual case.
FUD from the '90s is way past its sell-by date.
This has not been my experience and I'm greatly relieved that I haven't been subjected to such a hostile and destructive working environment in finance as yourself.
The correct response is always: "Show the benchmark numbers and make your case that the trade off is worth it." Then there is discussion on how compelling a case has been made.
Where do you work that allows you to implement everything twice, once in C and once in C++, for a proper comparison to be made?
(I realize that's not quite what you said, but if we're going with 'benchmark', then presumably those places have already done the benchmarks and decided that C++ is generally superior performance-wise.)
Micro benchmarks sadly have a way of showing nothing much at that end of things. Showing it's no worse/better doesn't even mean it's no worse if the additional/reduced pressure on caches doesn't result in much in the way of additional/reduced cache spills. So you end up doing mirco optimisations that each, taken alone don't do much. But when you get them all together you cross a threshold that has a considerable improvement. I believe SQLite did something like this although probably in a more restrained fashion as they have other goals than being the lowest latency solution against similarly motivated competitors.
Then of course at some point you get a reputation for success so you show the problem and the numbers identifying it and just say "I want to invest X of my time trying Y which I believe has a reasonable chance of helping" And you are told to focus on that and please let them know if you have any more good news. ;-) Sometimes your ideas are genuinely a wash and not worth merging but it is noted that it was worth trying and you're thanked for your efforts.
As somebody else noted in this thread the game has moved beyond much of this kind of thing in some, possibly many instances.
Whatever your technology choice you would expect to have to make a case, using evidence, and have that case properly listened to (or why did they hire you?). For performance critical technology you would expect that evidence to include benchmark numbers.
Any other approach to considering technology suggestions, involving "laughing out of the room", in the absence of evidence is completely unprofessional, very silly, utterly rude, purile, immature and wholly unacceptable. (And just quietly on that basis alone, I'd be pretty confident my solutions are faster than any put together by a team that ignores evidence and belittles talent. Again I say this is not about one technology vs another, this about "Laughing out of the room." Having said that I've sometimes used C and it has worked really quite well in those particular cases. I can say the same of C++ fwiw).
C no longer has them. Not since a standard that’s 20 years old (C99). restrict qualifier handles that.
Unfortunately C++ committee has not included restrict in C++, but it is available in all major compilers as an extension.
So much so that rustc regularly has to disable their noalias annotations because its pervasive noaliasing exercises rarely used LLVM paths and leads to miscompilation. Outputting noalias is currently disabled again in IR generation[0][1].
Note from downthread comments in [1] that it's completely possible to create valid C code which miscompiles on both GCC and LLVM (though GCC has been fixed since), it's just unlikely that a regular C dev would write the mix of unrolled loops, inlined functions and restrict annotations which triggers the issue.
And my understanding's it's since been fixed in GCC.
I don't doubt for a second there will be new miscompilations discovered after that one's fixed though.
Can you point us to a concrete benchmark to illustrate this?
There's a `restrict` keyword in C99.
> const really means const, where in C the compiler has to assume any pointer-to-const might be use to write through
Lookup what `const int *const ptr` does in C.
What the parent is saying is essentially right. C++'s compile time polymorphism and lamdas can allow faster than C given the right subset of language chosen. For instance std::sort regularly outperforms qsort(3).
Yes, if by that you mean "idiomatic C++ as C++ programmers write it".
It's the inexperienced "C/C++" (no such thing, BTW) that are 'choosing subsets', and doing it wrong 90% of the time.
Also, from the paper's Conclusions: "The cost of [Rust's] safety and security features are only 2% - 10% of throughput on modern out-of-order CPUs." 10% network throughput is a lot.
We specifically do not give you a flag to control this behavior, but you can choose to call different functions to use unchecked access.
It just seems like this sort of question is going to recur, and being able to persistently track the overhead of checking (it would allow you to monitor specific performance improvements) is much nicer than having someone do a one-off experiment.
We already have one “secret” escape flag feature, and people do use it, as much as we don’t talk about it and tell people not to use it when they find it.
The odd one out is overflow, and that’s only because it’s well defined (a “program error”) and not UB to overflow in Rust. This gets checked in debug but not currently release, though the spec allows for it.
https://doc.rust-lang.org/std/primitive.slice.html#method.ge...
Who wants a compile-time flag that makes valid programs have undefined behaviour? Nobody, especially when you consider that UB in any language really does mean undefined: in the best case the program crashes, in the worst it deletes all your files.
What's wanted is a way to tell the compiler "no, in this specific case which I have determined to be a bottleneck in my program, I want to omit bounds checking because due to XYZ it's impossible for the index to ever be out of bounds" and that's exactly what this method provides.
If they are right, and bound checks are the issue, doing this should recover the performance difference.
yeah, I wonder in which world they live. If I could sell a limb to get 10% more audio plug-ins in my DAW, you could be sure that my bedtime book would be "Life pro-tips for quadruple amputees"
State of the art for a lot of these use cases is still the kernel driver which is ~7 times slower. Sure, all that stuff is moving to XDP/eBPF/AF_XDP, but that is still ~20-30% slower than a user-space driver.
Also, these 2-10% only show up when underclocking the CPU while running the unrealistic benchmark of forwarding packets bidirectionally on only one core (trivial to parallelize).
In the end it's about 6-12 cycles spent more in the driver. That's not a lot if you have a non-trivial application on top of it.
I really do love this language.
And I believe the checked math can be eliminated just by explicitly stating you want to use unchecked math. It doesn't require unsafe to do so.
It can and often is. Don't use [] to index into data if you can afford not to. Anecdotally, rustc is also much better at generating SIMD-friendly code with iterators than idiomatic C/C++, but that depends largely on what you're doing.
[1]: https://github.com/rust-lang/rust/blob/f0b58fcf03391a91f7422...
fn loop(a: &[u8]) {
assert!(a.len >= 20);
for x in (0..20) {
let y = a[i];
//Do something with y
}
}
Adding the assert before the loop will remove the bounds checks happening on each iteration.Low effort commenting is usually shunned here, yet the ever prevalent "source?" seems to get a free pass all the time.
Really people should say: "source? Because I tried https://www.google.com/search?q=rustc+is+also+much+better+at... and found no sources whatsoever about this issue that has been discussed to death on dozens of forums yet I was somehow incapable of finding a single thing on the matter"
Why should someone spend time typing out easily searchable content for you? In fact, why should forums with a focus on high quality content even answer you?
Anyone who asks for sources should be required to do the same on demand. Whenever, wherever.
(This is just for the normal operators, if you use e.g. checked_add() or wrapping_add() then you can be explicit about what behavior you want.)
[edit: oops, the overflow checks were only enabled for a separate test, see note from the author below]
eg, once the difference between using a sign and unsigned value in a loop was causing tustc to not be able to optimize out the checks and resulted in terrible performance for that loop, but it was non-trivial to figure this out
Is there any other downside? Electricity consumption / heat? Evicting other stuff from cache?
6 cycles for bounds checks that the branch predictor never had to rewind on is nothing in comparison to saving a couple trips to L3.
Dramatically better L1 and L2 cache behavior. It seems clear that the additional instruction load of the Rust driver is partially made up by the excellent cache utilization.
This "Rust vs C" document is just one part of a larger analysis of network driver implementations in many languages; C, Rust, Go, C#, Java, OCaml, Haskell, Swift, Javascript and Python. Have a look at the top level README.md of that GitHub repo.
Also, isn't it unintuitive that branch mispredictions go up with larger batch sizes? Wouldn't there be fewer branches per unit time?
[1] https://github.com/duneroadrunner/SaferCPlusPlus/blob/master...
It's mostly vmem until / unless the data actually gets used though, no?
The effects of larger memory usage don't become obvious until other applications start contending for it and/or swapping happens, and it's conveniently also something that is not as easily blamed on one application "being slow", which is why it doesn't receive nearly as much attention as it should.
We'll have a VirtIO driver soon, but that's bottlenecked by the hypervisor and not really useful for performance tests.
Or did I miss something more nuanced?
It will behave different at the level we are looking at here. It's easier to use real hardware; we specifically chose this NIC because it's probably the most common 10G NIC on servers.
(1) Runtime. Even though C has "no" runtime, there is some runtime overhead: Variable allocation / de-allocation and alignment. Function invocation / call stack setup. Et cetera. I don't know enough about Rust to understand what its exact "runtime" is like, but I'd bet it's not exactly like C. (Rust is strongly-typed, is it not? Does it do run-time type-checking?) Exception handling in particular requires a non-negligible amount of run-time overhead and may account for a significant proportion of the difference between the performance of Rust and C.
(2) Optimization. Rust and C are going to be compiled with either GCC or LLVM. The way both work is they compile the program to an internal representation of opcodes, which then get optimized and platform-specific, optimized machine code is then emitted. In some cases the specific set of opcodes or optimizations used with various conventions / data structures may be more efficient or less efficient. Over time this will improve.
To be more specific: errors in Rust are either propagated by function return values (usually in the form of `Result` or `Option` types) which do not require any kind of runtime support, or by panicking, which unwinds the stack for clearing-up of resources and then halts the running thread. (Panics cannot be caught, although they can [EDIT: sometimes but not always; see burntsushi's comment below] be observed by a parent thread if they have occurred in a child thread.) Rust's "runtime", therefore is negligible, much like C's: it consists mainly of functions which can be called for things like stack unwinding or backtrace support.
Do note the caveats in the docs though. It isn't guaranteed to catch all panics. Indeed, unwinding can be disabled completely with a compiler option (instead, panics will abort).
"Because RefCell<T> allows mutable borrows checked at runtime, you can mutate the value inside the RefCell<T> even when the RefCell<T> is immutable."
*source https://doc.rust-lang.org/book/ch15-05-interior-mutability.h...
EDIT: Sorry, I don't mean 'runtime type checks' are slowing down Rust, but rather that Rust performs more general runtime safety checks (like RefCell).
It is.
> Rust is strongly-typed, is it not?
Yes.
> Does it do run-time type-checking?
No.
> Exception handling in particular requires a non-negligible amount of run-time overhead and may account for a significant proportion of the difference between the performance of Rust and C.
Rust does not have exceptions, it has panics (fatal errors). It is correct for a panic to abort the program. You can provide an user-defined panic run-time that does whatever you want (unwinding, aborting, looping forever, `ud2`, etc.).
Yes, at compile-time.
> Does it do run-time type-checking?
No. The closest thing is the occasional vtable-based dynamic dispatch.
> Exception handling in particular requires a non-negligible amount of run-time overhead
Wouldn't the side-table approach be used? That has essentially zero cost, if an exception is not thrown.
Specifics aside the broader point is that the runtimes between the two languages will differ.
g++ exceptions have been touted as zero-cost for the happy path.
https://stackoverflow.com/a/13836329
http://www.hexblog.com/wp-content/uploads/2012/06/Recon-2012...
Take a look at this: https://imgur.com/lPOPj1G
You see that difference? That's not rust producing less-efficient code. That's the more complex rust runtime.
Think it's an artifact of static linkage? Guess again.
But IIRC rust doesn't statically link glibc by default.
So the difference in runtime overhead is more than 10x the machine code size. That doesn't translate to a 10x slowdown and a lot of that is probably baked-in optimization but rust certainly has a runtime and associated overhead and it has a lot larger runtime than C.
If true, can you say the difference is not due to chance?
(fwiw the GM that I see — whether the scores are based-on elapsed secs, cpu secs or "busy" secs — are a little slower for the Rust programs.)
Perhaps the median score of the Rust programs is faster?
https://github.com/ixy-languages/ixy.swift/blob/master/perfo...
Please qualify the title: it's not generally the case.
> We are at ~20 bytes of allocation per forwarded packet in Java.
C# and Go have much better facilities to avoid heap allocations.
There's an unsafe method to not do bounds-checking, keeping in mind that indexing outside the collection is UB. It's usually a better idea to e.g. use iterators, or try and nudge the optimiser towards removing the bounds checks.
> disables it for optimised builds
A compiler flag to add UBs to a valid (though not correct) program is not considered a great idea by the rust team.
The one exception I'm aware of is that integer overflow panics in debug builds, and silently wraps in release builds. But in most other cases, there will be different separate methods with different semantics, requiring an unsafe context as appropriate.
Why? How can Fortran and PL/I beat assembler and C?
In particular, first, Fortran can easily beat C in subroutines that receive multidimensional arrays as parameters. Here PL/I also can beat C for the same reasons. Second, PL/I beats both Fortran and C in string handling.
How, why, what the heck is going on? In simple terms, first, Fortran gets to compile the multidimensional array handling within the language and C does not: In C, the programmer has to write the array addressing logic (e.g., row major or column major) that looks to the C compiler like just more code where the compiler has to treat that handling as general purpose code; the Fortran compiler KNOWS that the work is array handling and gets to make better uses of registers and to store intermediate results where the Fortran source code can't see them and, thus, take some liberties. That is, in Fortran, the array handling is in the language where the compiler can take liberties where a C compiler has to treat the work as ordinary code and not take the liberties. PL/I has the same advantages. Second, similarly for string handling in PL/I.
In particular, commonly in C and Fortran, string handling is via subroutines that to the linkage editor look like external references that must be linked. That indirection, stack manipulation, register save, restore, etc., PL/I doesn't have to do.
Scientific, engineering, analytical code is awash in multidimensional arrays, and there Fortran and PL/I can beat C. Now nearly all code is awash in string handling, and there PL/I can beat both Fortran and C.
For assembler, the old remark was that in practice an assembler programmer would write his own code that was less well designed and, thus, slower than C, Fortran, and PL/I. Further, the assembler programmer would be tempted to have a large library for arrays and strings that would be external subroutine calls likely with the overhead. Sure, in principle, assembler should win, but in practice writing code good enough to win is usually a bit too much work.
More generally, compiled functionality offered directly by the language can be faster than libraries of external subroutines, methods, etc.
String handling, on most modern toolchains, mostly goes to inline functions or builtins that the compiler has been (rather pragmatically, if a big disgustingly) made aware of. It's very unlikely that strcpy or memmem is going through external linkage.
The relevance here: C isn't the fastest thing around and can be beaten. Maybe similarly for Rust.
For PL/I and strings, for the IBM versions on S/360 and S/370, the compiler might have used some of the hardware instructions for string handling.
I'd be surprised if in C strcpy, etc., were not still external: They USED to be, and then someone might have written their own version, e.g., for their own versions of strings, and linked to it; for compatibility, strcpy would about have to be an external function call still.
Real X(20, 30,40), all
Call addall(X, 20, 30,40, all)
and have Subroutine Addall (Z, L, M, N, Result)
Real Z(L, M, N), All, Result
Integer L, M, N, I, J, K
Sum = 0.0
Do 100 I = 1, L
Do 100 J = 1, M
Do 100 J = 1, N
All = All + Z(I, J, K)
100 Continue
So what is good here is that in the
subroutine the parameter Z
gets its array bounds PASSED
from the calling routine, the
statement Real Z(L, M, N)
honors those bounds, and the
code then does the indexing
arithmetic (row major or column
major, I don't recall which)
using the bounds passed as
arguments to the parameters
L, M, N. That is, in the subroutine
we can have the array bounds as
parameters, and still Fortran does
the array indexing arithmetic.Can't do that in C: In C the programmer has to do array indexing with their own code in the subroutine. Thus to the compiler this code is just ordinary code and has to be treated as such. In contrast array indexing Fortran does is not from ordinary code thus permitting Fortran to make better use of registers and, for example, leaving intermediate values in registers and not writing them back to storage in variables known to the source code.
Here vectorization has nothing to do with it.
Bluntly, C doesn't support arrays, and that's a bummer for the programmer and also execution speed.
My point is on topic because this thread is about C performance, and I've brought up the point that functionality, in this case array indexing arithmetic, defined in the language and implemented in the compiler can be faster than the programmer implementing the functionality in their own code, especially, in the case of strings, if that implementation is via external routines.
I thought that this was all simple and clear.
C compilers (with optimization on) don't spill intermediates either.
Your decades of experience are appreciated, but apparently your decades of experience don't cover looking at what optimizing C compilers learned to do in the last 30 years or so.
> Bluntly, C doesn't support arrays, and that's a bummer for the programmer
That's true.
> and also execution speed.
That isn't, or at least you haven't demonstrated it.