61 points · by ingve · 10y ago · 90 comments
Judging by the benchmark game [1] https://benchmarksgame.alioth.debian.org/u64q/rust.html Rust has almost caught/eclipsed C. The biggest issue for the marks its behind on are stabilized SIMD support in Rust (nightly has it but its not finalized on an RFC level).
[1] Look I'll save you the comment. Yes the benchmark game isn't always indicative of real world performance. Its a bunch of small micro benchmarks that demonstrate basically how quickly Regexs/Hashing/Math are in each language. While that's not everything you do when programming its a decent chunk.
Does anyone have a link to the source used in these tests?
http://benchmarksgame.alioth.debian.org/why-measure-toy-benc...
Yes, just a starting point --
http://benchmarksgame.alioth.debian.org/dont-jump-to-conclus...
For instance, the unspecified order in which function arguments are evaluated, or the operands of most operators, or initializers in a declarator and such. In combination with certain uses of side effects, this creates undefined behavior (and even when not undefined, it can create surprises and bugs). This is purely a C semantics problem, not connected to the way the machine works, or the large scale way in which programs and their data fit together.
And let us note that even if evaluation order is pinned down by the language semantics, the compiler can still re-arrange it anyway, when it can recognize opportunities in which re-ordering evaluation makes no difference (the result, including all effects, are still as if it had been left to right).
Contrast that with, say, bounds checking arrays, where the neglect to do so is justified by the fact that pointers don't carry the size information, since they are mapped to machine addresses, which is a translation decision that has deep, non-localized semantic implications. Wider pointers don't fit into a register, which affects how they are passed between functions. They take up more space in every data structure which has pointers, and so on. There is a tangible, external difference, and performance impact.
A reasonable dialect in C should sacrifice safety only when there is a tangible performance issue.
Undefined behaviors at translation time (particularly in the preprocessor!) should be completely banished.
Here is one: there is no reason why a preprocessor token pasting operation (A ## B) which results in an invalid token should be undefined behavior. The execution of the preprocessor is quasi cost-free. Whether or not two elements pasted together to form a valid token can be checked, and diagnosed. The few preprocessor cycles which that requires are worth it!
The fact that it's not practical to banish or diagnose all undefined behaviors (nor desirable or reasonable to do so, since UB is an area for useful extensions) shouldn't be used as an excuse not to eliminate some of the silly ones.
int f(int* p, int* q){return ++p + ++q;}
It depends! It depends on whether p == q. If so, it is not defined, and on high optimization levels, compilers will tend to give the wrong answer, but on low levels not so much. I bet a lot of people (but probably not all) would be willing to take the speed hit so that this becomes well defined, as it is in most other languages. (Note: I haven't fact checked anything I wrote here; no doubt some language lawyer will correct me if I'm wrong.)
But since C99 we have had a tool by which we can tell the compiler, "trust me, p != q". Namely:
int f(int * restrict p, int * restrict q) { ... }
So with this, even if we have strict left to right order, it can still reorder the code the same as before.I also agree with you about bounds checking arrays: this is the wrong problem to start from when there is so much lower hanging fruit.
I want to agree with you about unspecified evaluation order, but I worry about possible side effects. If tomorrow someone waved a magic wand and all C compilers have a command line switch --left2rite that forces left-to-right evaluation order, how many programs that currently "work" by accident will suddenly break if this switch is enabled? Maybe it's very few, maybe so few that the change is a net benefit. But are you sure? The programs most likely to break are not the ones with the best test suites. I will say this though: implementing this switch is a good idea anyway, for at least two reasons. New programs can use it (at least if they don't worry about portability to a compiler that doesn't support it). More importantly, we can then start doing experiments to gather data and try to answer the question of how widespread the problem is. Until then, we'll never know.
> I doubt anyone is willing to pay 2x performance for their C code to be more friendly. If they were, why are they writing in C?
Beats me why anyone is writing in C full stop.
I fully agree. But this is not without tradeoffs: eliminating undefined behavior pretty much means (a) the performance and runtime overhead of a GC (most languages); (b) forbidding malloc (verified "mission-critical" variants of Ada, C, etc.); (c) requiring programmers to learn a lot of new concepts (Rust†). I do think that there is rapidly becoming little reason to use C except for throwaway programs, and as an industry we need to be more open to (c) if we are ever going to move beyond making the same memory management mistakes we've been continuously making since the 1960s. But I also understand the reasons why programmers continue to choose C and C++.
† It's interesting to me that the biggest reason C++ programmers give for bouncing off Rust is fundamentally "I want my undefined behavior back", though very few actually word it like that.
1. Interoperability code with some library or the OS.
2. C as the closest thing to a portable assembler there is (e.g. to implement something like the Ruby interpreter).
What I need for this isn't perfect safety; it's the ability to reason with some confidence about the code I'm writing (I may want to be able to rely on code review by merely mortal programmers or create my own tools to enforce this). If I wanted a safe, expressive language, I wouldn't use C in the first place.
But right now even something as simple as a malloc implementation is riddled with traps even for reasonably skilled programmers. The Linux kernel uses -fno-strict-overflow and the FreeBSD kernel uses -fwrapv because the price to be paid by enabling the undefined behavior of -fstrict-overflow was too high.
If by "interoperability" you mean "binding a more modern language to a C library", no argument there. Binding to C is a legitimate reason to write C.
> 2. C as the closest thing to a portable assembler there is (e.g. to implement something like the Ruby interpreter).
My question is: why do you want a portable assembler? Why not write Ruby in, for example, Go? It could certainly be done; look at JRuby, for instance.
The vast majority of the time, the answer to this question is "performance". Which brings us back to the point of the article. Without compiler optimizations enabled by undefined behavior, you can easily lose 2x performance or more. A 2x performance loss for MRI is unacceptable.
Malloc implementations embody this even more. In fact, it's kind of hard to think of any piece of code that's more performance critical than malloc. Many large applications (apps, games) spend 10%-20% of their time in the malloc and free functions. Allocator performance is so important that Facebook and Google have invested a huge number of man-hours into these two routines (jemalloc and tcmalloc respectively). It all comes down to performance again: under these extreme contraints, malloc simply can't afford a 2x performance loss. A Friendly C that produced slower code would have little chance of being adopted by allocator writers.
Disallowing undefined behavior simply means the result is defined behavior. Might be safe, unsafe, any number of things. Just clearly that to developer and tools.
In your proposal, how do you propose to solve the load-load forwarding issue described in the article?
If every important program on your computer (The ones written in C -- OS, web browser, text editor, language interpreters, etc.) suddenly became twice as slow for "safety", assuming you never modify those programs on your own, you'd probably be a little bit cross right? You wouldn't really care that the language is safer, you'd just notice your top of the line computer is suddenly feeling pretty slow.
Exactly. Read the comments on literally any thread about browsers on HN to understand why sacrificing that degree of performance is unacceptable.
i can list many reasons why i continue to use C, please, there's no need to suggest or imply that C has outlived its usefulness - it clearly hasn't.
This is what "undefined" means: what it say! It doesn't mean "illegal", and it doesn't mean "bad".
However, "undefined" does mean "illegal". Not only does the standard not say what will happen, the standard says that such behavior is not allowed in well-formed C programs. C compilers, then, tend to optimize based on the assumption that certain behaviors will not happen. This can causes weirdness when they encounter programs that exhibit this behavior - and yes, such programs have a bug. But often, the bug manifests in an even stranger way. Check out the work of John Regehr for more (academic publications: http://www.cs.utah.edu/~regehr/papers/; blog: http://blog.regehr.org/).
Embedded software? All of the platforms I work on provide C/C++ compilers and driver libraries that are C only. I'm working on an ARM Cortex project right now and there isn't even C++11 support.
So, no, C is not easy to reason about. Nor are the tools that can cheap if you want low, false positives.
No, people write C because it's the only choice in many cases. Like where you need total control over memory management, or because you want to interact with a kernel or hardware directly, or because you want to write functions in the lingua franca of compiled code.
I wouldn't be quick to use it for a large scale project which does not require 110% performance but for anything were performance is your nr. 1 goal I've found it quite refereshing.
int foo(int* p_int, float p_float) {
int a = *p_int;
*p_float = 0.0;
return a - *p_int;
}
Should that be `float* p_float`?To me this is the fundamental issue with the friendly/boring C proposals. The whole reason to use C/C++ anymore is for performance, in return for which you are responsible for certain things - like using only defined behavior.
If you are writing e.g. crypto code, why not use a higher level language that provides more checks and guarantees, and is generally easier to reason about? Or segregate the performance-critical "engine" type code into C++ and use something higher level for everything else?
I don't disagree with this piece, but I think it's missing the thrust of the "friendly C" argument. The desire (at least I feel it) is simply for the compiler to "do what I mean", rather than making unexpected optimizations based on undefined behavior. There is no expectation that the resulting language will be "safe" as the word is normally used. If one wants safety (and can accept the performance compromise that this entails) then there are alternative languages to choose from.
Instead, "friendly C" has much simpler ambitions: replace undefined behavior with compiler specified behavior. The spec could simply guarantee that if you read an out-of-bounds value, that the compiler will generate assembly that attempts to read the value at that address. Having the program segfault on the attempt is perfectly acceptable. The only thing that is not acceptable is for the compiler to reason that the read will be out of bounds, and thus decide to omit the error checking code that follows.
You didn't understand the example. Your proposal destroys load-load forwarding, as the article demonstrates.
Certainly this may be true, but I've re-read it again with your prompting and still think I understand it.
Your proposal destroys load-load forwarding, as the article demonstrates.
I'm fine a compiler that optimizes out the write to a value on the stack on the assumption that this can't be the same address as a passed pointer, whether that parameter is an int or float. I'm fine with a compiler that creates assembly that simply returns 0 here, with or without 'restrict'.
That you and the author think this example represents a conflict with John's "friendly C" proposal makes me more certain that you don't mean the same thing by "friendly C" as I do, or as I think John does. Really, I think we're asking for something quite different, and much simpler to achieve.
In any case, if you require that a compiler emit an actual load instruction for every memory access then you've destroyed SROA, which is one of the most important optimizations, especially in C++. Without SROA C++ can easily be 4x-5x slower.
I want to write C as high level assembly. If I put values in registers and reuse them, then I'm opening myself for the same kind of problems as if I'm writing C and not doing explicit memory reads.
There is something to controlling aliasing, though. It basically leads you to Rust's (or ISO Core C++ with lifetime profile) memory model. :)
designing a new language somewhat hinders this - unless some sort of source to source translator tool could be produced, perhaps.
in my opinion, C should roughly stay the way it is. we have higher level languages which provide a lot more safety, and we have the clock cycles available to absorb the reduced performance that they may incur. more importantly, compiler implementations for these languages can continue to reduce the gap between "high level" and "native C".
EDIT: " I doubt anyone is willing to pay 2x performance for their C code to be more friendly. If they were, why are they writing in C?"
Because it's friendly? Because the cost/benefit in terms of avoided bugs and productivity is worth it to the company/shop.
Depends on what the semantics of that hypothetical Go variant are. How would that Go variant solve the load-load forwarding problem described in the article?
> Because it's friendly? Because the cost/benefit in terms of avoided bugs and productivity is worth it to the company/shop.
I think the point the author was making is that if you are OK with that performance hit you're probably OK with Java, which banishes undefined behavior in the C sense entirely.
not unless you use the restrict keyword...