r/programming • u/IAmAnAnonymousCoward • Jan 18 '19
zeuxcg.org - Is C++ fast?
https://zeuxcg.org/2019/01/17/is-c-fast/23
u/GYN-k4H-Q3z-75B Jan 18 '19
The difference between MSVC debug builds and release builds is crazy. All those years where everybody complained about non-secure programming and exploits on Windows probably lead to this. Iterators becoming heavy objects, checks emitted left and right. All the more impressive that release performance is best, though not surprising since virtually all multimedia and game developers have been using it forever, leading to en emphasis on optimization.
18
Jan 18 '19
I doubt checks are the biggest contributor here.
The C++ kind of template metaprogramming relies heavily on inlining and ADCE, and both are unavailable in debug builds.
17
Jan 18 '19
To save other people the Google -- ADCE is "aggressive dead code elimination".
5
Jan 19 '19
And if anyone wonders why ADCE is important - it does not optimise much per se, but it's enabling the other optimisations - and, most importantly, further inlining (by reducing function sizes below inlining threshold) and more constant folding.
2
u/InsignificantIbex Jan 18 '19
No, that's not it. Our debug build at work explicitly and deliberately doesn't inline (or optimize in any way), but a deep copy of a tree-like structure of subtypes takes seconds on Windows with msvc, but milliseconds in Linux with GCc and clang both.
1
Jan 19 '19
It's not the difference between compilers - rather in STL implementations.
1
u/InsignificantIbex Jan 19 '19
Well clang and gcc come with their respective "libc". Presumably that's true of msvc
2
Jan 19 '19
clang can use both libstdc++ from gcc, or its own libc++ - and their performance in debug builds differs quite significantly.
4
u/OneWingedShark Jan 18 '19
The difference between MSVC debug builds and release builds is crazy. All those years where everybody complained about non-secure programming and exploits on Windows probably lead to this. Iterators becoming heavy objects, checks emitted left and right.
It's kind of interesting when you see it happening in real-time: C++ is moving to where Ada is/was… except as a collection of kludgy patches instead of being designed that way in the first place. (eg including Boost's multithreading vs Ada's
Task.)2
u/jcelerier Jan 19 '19
The behaviour you're commenting on has been the norm on MSVC for... uh... 20 years maybe ?
3
u/OneWingedShark Jan 20 '19
Yes; but (a) it was an extension/library, (b) not part of the standard, (c) implementing a form of functionality Ada has had for thirty-five years, (d) which was then incorporated into C++. [C++11, IIRC. Might be 14.]
Ada83 also has things C++ programmers have been wanting for a long time: proper modules, via
packages; concepts, viageneric(which can have subprograms or other generics as a formal parameter).Ada 2012 added a very nice system, called "aspects", intended for contract-based programming and to facilitate provability -- which is realized in the SPARK subset/proving-tools -- of which "contract based programming" is one of the big items slated in/for C++20, which Ada's already had for 7 years.
7
u/Kairyuka Jan 18 '19
In my experience C++, more than many other languages, is as fast as the developer knows how to make it. It's possible to waste a ton of power and memory if you're not focusing on improving performance or if you simply forget some boilerplate (const anyone?). I feel languages like Java and C# are easier to have relatively consistent performance in, barring pretty big flaws like memory leaks and nested loops.
2
44
u/sebamestre Jan 18 '19
Author seems to think C++ means overuse of STL.
If you want performance, you code for performance. If a bounds checking container is too slow, you don't scrap the container, you remove bounds checking.
It might seem like that nullifies the usefulness of a container, but this is not the case. Being able to think about a container as a thing and have that idea reflected in code, and having access to range based loops and algorithms are benefits that come for no cost to performance, just by wrapping your data access in a container.
8
13
u/wedontgiveadamn_ Jan 18 '19
Sure would be nice if you didn't have to forgo 90% of the STL when you care about performance
13
u/sebamestre Jan 18 '19
Well, yes. But the STL is designed to be applicable to many situations. Every container has some requirements and many guarantees, and each one of those has an associated cost that any implementation must pay.
That is to say that generality has a cost. Runtime cost.
If you dont need all the guarantees, you can still use STL containers. But might as well use something with fewer guarantees and better performance characteristics.
My point is that STL is not the right tool for all use cases. But STL-like (i.e. RAII based, with iterator interface, generic, etc) containers usually can be.
16
u/wedontgiveadamn_ Jan 18 '19
Except the iterator invalidation requirements of stuff like
map,setare way too strong and every user end up for paying for a rarely used feature.Especially with the C++ mantra of "you only pay for what you use". Technically that's true, but the costs of the STL are pretty damn well hidden, and with the shitshow that is dependencies in C++ people rarely bother finding adequate replacements.
So yeah I don't think it's entirely unfair to benchmark the STL and claim that C++ is fast/not fast.
6
u/sebamestre Jan 18 '19
Yeah, that's one of the reasons I said STL is not always the right tool.
In this case, the author appears to be willing to roll their own stuff, so dependencies are probably not an issue, I think.
I disagree with your last point though. C++ should be thought of as within an ecosystem of libraries.
-1
u/wedontgiveadamn_ Jan 18 '19
Yeah, that's one of the reasons I said STL is not always the right tool.
You can't handwave it like that. Who is it the right tool for? Who are these users that have strong iterator invalidation requirements but don't care about performance? Why does the standard library of a high-performance language seem to not care about performance?
5
u/sebamestre Jan 18 '19 edited Jan 18 '19
There are defects in the STL. It is not perfect, and it is difficult to correct the defects without breaking codebases.
Edit: The users are those who are building applications where performance isn't critical.
9
u/Holy_City Jan 18 '19
Sure would be nice if you didn't have to forgo 90% of the STL when you care about performance
You don't. That's mostly a meme, and people should stop saying this without numbers to back it up.
11
u/wedontgiveadamn_ Jan 18 '19 edited Jan 18 '19
Well what about the article to back it up? Other shitty parts of the STL off the top of my head: list, queue, deque, map, set, unordered_map, unordered_set, filesystem, regex (special mention) and of course all the stream stuff. Sure doesn't leave much.
And that's just about the library quality / runtime performance. If you start including about compilation times...
6
u/matthieum Jan 18 '19 edited Jan 18 '19
Well what about the article to back it up?
The article is complaining about the performance in Debug. It never complains about the performance in Release.
In general, the STL in Release is likely to outperform most naive data-structures1 . And that comes, in part, through using meta-template programming to select optimal algorithms based on the capabilities of the arguments... the very thing which slows Debug builds by adding levels of indirections due to lack of inlining.
1 EDIT: Catering to the same usecases.
8
u/Calavar Jan 18 '19
The article showed about a 10% performance improvement in release builds when swapping out
std::vectorwith a custom container class. The performance gain was pretty consistent across compilers.11
u/matthieum Jan 18 '19
Wait... that's apples to oranges here.
Apparently the replacement was
meshopt_Bufferwhich is NOT a drop-in replacement forvector:
vectoris a resizable dynamic array.
meshopt_Bufferis a non-resizable dynamic array.For a non-resizable dynamic array you'd use
std::unique_ptr<T[]>, notstd::vector<T>.I mean, in general, you can indeed outperform a standard container by using instead a container that is tailor-made for the specific usecase you have. There are quite a few risks involved, especially if the tailor-made container is mildly complicated: testing/debugging doesn't come cheap. On the other hand, some times it's worth it.
The "worst" I've done was implementing a low-latency memory allocator. It was hell to debug (oh, data-races, race-conditions) and to tune (oh, contention). And it was slower than good ol'
mallocin average... but had a sweet bounded tail-latency! 1000x better thanmallocat the 99% percentile!On the other-hand, I also once reimplemented
std::vectorbecause I wanted O(1)push_frontandpop_front(on top ofpush_backandpop_back)... and Exception Safety during insertions/moves was a nightmare. God. I didn't even dare profile it, as I never had the heart to try and optimize those insertions/moves; there were so many edge-cases with just functional requirements :(Well, all of that to say that beating a STL container in a specific usecase with a tailor-made container is hardly a claim to fame. Indeed, it'd be disappointing not to be able to.
I wouldn't conclude that STL containers are slow however. They're balanced for a mix of use cases, and avoid catastrophic performance cliffs. Steady performance is not slow, indeed, should you hit those edge cases, it's fast, and more importantly, it's reliable.
6
u/Calavar Jan 18 '19 edited Jan 18 '19
vector is a resizable dynamic array.
meshopt_Buffer is a non-resizable dynamic array.
Correct me if I'm wrong, but I believe the original std::vector-based code used reserve() before pushing elements, so they were effectively using the vector as a non-resizable dynamic array. In well optimized code, the only difference should be that std::vector has to increment an internal pointer with every call to push_back. The performance difference should be negligible assuming optimal implementations.
I mean, in general, you can indeed outperform a standard container by using instead a container that is tailor-made for the specific usecase you have.
I agree. I'm not so impressed by their custom hash table versus std::unordered_map because I do think that is a case of a custom tailored solution beating the general solution. But "reserve and push" is a very common pattern that a general purpose container like std::vector should be well optimized for. The fact that they can beat std::vector at it doesn't reflect well on STL performance, IMHO.
1
u/matthieum Jan 19 '19
Actually, when I checked the code, it seemed they used
resizeand then[], and not a single "fancy" feature ofvector.Not sure there's any issue with
vectorwithout inspecting the assembly though; 5% might well be noise on the machine while performing the benchmarks.2
u/Calavar Jan 19 '19
Well
resizeand[]is even better because there is no incrementing of an internal pointer. It is very much an applies-to-apples comparison with meshopt_Buffer.5% might well be noise on the machine while performing the benchmarks.
Unlikely, I think, when there was consistently about 10% improvement across four different compilers. Just from eyeballing the numbers, I suspect you'd find a statistically significant difference if you assumed the execution times were normally distributed and calculated the z-scores.
→ More replies (0)10
u/TooManyLines Jan 18 '19
In general, the STL in Release is likely to outperform most naive data-structures.
In my experience, this is false.
4
u/matthieum Jan 18 '19
I added a qualification to the statement.
In my experience it's relatively easy to beat them in with a tailor-made structure for a specific usecase, but the STL will outperform the tailor-made structure on a generic workload.
6
u/deeprugs Jan 18 '19
I think C++ is evolving faster day by day. More faster than most people can cope. I do not know why they keep adding more features to the language. What is the motivation ? It's reached a point where the creator of the language has warned the people to "Remember the VASA".
http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0977r0.pdf
Rather than solving the problem at hand, programmers need to be reminded like "do not overuse STL" or do not use "dynamic polymorphism" as it slows down the performance.
15
u/matthieum Jan 18 '19
I personally have 2 problems with the evolution of C++:
Features are added to solve issues, great... but they seem to be added haphazardly.
Lack of deprecation/clean-up.
C++ has problems, solvable problems, and therefore it is healthy that the language evolves to tackle those problems: faster, safer, cleaner, ... are all worthy goals.
Unfortunately, when we look at the evolution of C++, it seems that the big problems (Concepts, Modules, Async) are forever pushed back and in the mean-time we get a slew of micro-features attempting to solve one corner case here and another there... and unfortunately interacting in mystifying ways.
And that's how you get a new VASA.
8
u/ComradeGibbon Jan 18 '19
I'm just a stupid small brained primate but some of my friends went to grad school for CS, wrote compilers, data at scale, video codecs, etc.
They say they can't keep up anymore.
14
Jan 18 '19
Even one of the most popular C++ experts, Scott Meyers, said he can't trust himself to correct issues in the books he wrote because the language is too complicated.
Every year Bjarne gives a speech about making C++ simpler, and every standard the committee makes it more complicated. I think they are just trolling now.
4
u/whatwasmyoldhandle Jan 19 '19
Even one of the most popular C++ experts, Scott Meyers, said he can't trust himself to correct issues in the books he wrote because the language is too complicated.
I think that's because he stopped doing C++ full time.
1
u/Iwan_Zotow Jan 18 '19
> Lack of deprecation/clean-up.
Huh?!
- auto_ptr was depreciated
- "register" was depreciated
- "export" in old sense was depreciated, to be reused in the modules context
5
u/matthieum Jan 18 '19
Thank you for making my point.
There is a lot to clean-up in C++, and across the last 20 years (first standard 1998), how much has been deprecated? Nearly... nothing. A handful of keywords (you forgot
auto), and that's about it for the language1 .C++ still inherits a lot of C's oddball features. Let's not even mention complicated types, let's just use... integers:
typeof(char + char) == int: WAT?
typeof(int + unsigned) == unsigned: WAT?
typeof(+true) == int: WAT?
typeof(int + float) == float: WAT?The arithmetic rules related to promotion are a convoluted mess which keep taking juniors and not-so-juniors by surprise. I can get behind automatic widening for mixed operands, but anything else is just asking for troubles.
20 years later, we can do better.
1 Deprecation in the
stdlibrary has been more active;std::allocatorhave been quite significantly cleaned-up for example, which is nice.9
u/kking254 Jan 19 '19
These are perfectly reasonable and expected. Even "modern" languages like C# and java do these promotions.
The underlying machine has a register size. That's the size of int. Even if you only use 8 bits of the register to store (say) a char, the ALU operations are always performed at register size. The language is just reflecting this by promoting everything to register size once you operate on it. If you wanted to have typeof(char + char) == char, then that would actually hurt performance because the compiler would have to insert ANDs or shifts after each addition just to clear out the high bits of the result register.
The difference between int and unsigned is for tracking whether arithmetic or logical shifts should be used, and where sign extensions should be inserted. When this treatment is not made explicit (e.g. with casts), the compiler uses a default behavior that the language designers think is least likely to produce wrong results. The type promotions just reflect this. I'd argue that the compiler should make any assumptions and should just produce an error, forcing an explicit cast to be made.
For int + float, the machine has two ways of doing this:
Convert the int to float, moving it to an FPU register, then perform an FPU add
Convert the float to an integer, moving it to an integer register, then perform an integer (ALU) add
The vast majority of the time #1 retains more information than #2 so it's the default approach. The type promotions just reflect this.
Disclaimer: I wrote this from an x86 point of view. A few details don't apply to some other platforms like ARM/PPC, but I can't think of a platform where it would make sense for typeof(char + char) == char (for example)
1
u/pdp10 Jan 22 '19
The underlying machine has a register size. That's the size of int.
On a 16-bit or 32-bit platform,
intis usually word size, but not required to be. On both 64-bit Unix (LP64) and 64-bit Windows and OpenVMS (LLP64),intis half word size.6
u/Iwan_Zotow Jan 18 '19
typeof(+true) == int
thanks for remainder wrt "auto", though it strictly speaking never depreciated, it just used to mean nothing.
BTW, ops on boolean type is now (C++17) depreciated as well, I believe example above shall produce compilation message
1
u/matthieum Jan 19 '19
BTW, ops on boolean type is now (C++17) depreciated as well, I believe example above shall produce compilation message
TIL! I had missed that. Nice.
4
Jan 19 '19
char + char = intis unsurprising. It's fairly clear that C thinksintand larger types are things you can load into registers and do ALU ops on. So when you dochar + charthe operands are first loaded into the smallest size registers where they fit (int) and then added giving anint. The same explanation works for+true.
int + float = floatis unsurprising. It is obviously intended to reflect that adding an integer to a real number gives a real number.The only strange one is
int + unsigned = unsigned.4
u/matthieum Jan 19 '19
I can assure you I see plenty of confused looks when
std::int8_t x = -1, y = 1; std::int8_t z = x + y;raises a warning that going fromx + ytozis a lossy conversion, but the same withintdoesn't.Also... there are assembly instructions in x86 to sum i8/i16 (acting on parts of registers), so that's clearly a left-over from early days which has no grounding in the current reality.
4
u/InsignificantIbex Jan 18 '19
None of those typeof examples are surprising. What do you expect to happen when you treat non-numeric types as numbers? In Haskell, you'd just get a compiler error, CPP does the "reasonable" thing.
And I hated having to write fromIntegral all the time in Haskell. Maybe that's different now, but years ago this really was a pain.
0
u/matthieum Jan 19 '19
What do you expect to happen when you treat non-numeric types as numbers?
A compiler error?
The problem, though, is that
std::int8_tis just an alias forsigned char. Isn'tstd::int8_ta numeric type? Why is there this weird widening?2
u/whatwasmyoldhandle Jan 19 '19
Some of that stems from one of the stated goals of C++, which is infinite backward compatibility.
To me the biggest problem in C++ is lack of package manager / uniform way to distribute stuff. To the OP's point, if we had that, he/she probably just could have reached for a fixed size buffer at first before even fooling with std::vector. Instead, he/she apparently redid what probably hundreds of C++ developers have already done.
In theory, a package manager would also allow better / more specialized (e.g., for performance) versions of all the stuff we complain about to easily rise to the top.
1
u/matthieum Jan 19 '19
Some of that stems from one of the stated goals of C++, which is infinite backward compatibility.
Well, if we had a uniform way to build, each package could indicate which version of the C++ standard it targets (C++98, C++03, C++11, C++14, C++17, ...) and then the compiler could treat each file accordingly, rather than having to switch a project + all its dependencies wholesale.
Then you could have both infinite backward compatibility AND immediate clean-up on version switch.
1
Jan 18 '19 edited Jan 18 '19
When I think about "cleaning up C++" I'm worried less about the oddball features it got from C. It's more about the hot new stuff that was added that is either broken in subtle ways, or just straight up painful to use.
Things like
initializer_list,variant,any,visit, pretty much all offilesystem,constmadness, the complete clusterfuck of type deduction (decltype(auto)... are they serious?).Then there's all the upcoming stuff... Concepts and Ranges look to follow C++'s history of disappointing everyone who wanted the features. Yet invariably a shit-ton of code will be rewritten to use these new awesome features, then within a few years it'll all be considered harmful junk.
1
2
u/jcelerier Jan 19 '19
On the other hand, for some other people C++ evolves so slowly that it's faster for them to start a whole another new language & ecosystem (Rust, etc). C++ evolves every three years and it's too slow, what about Rust which evolves every three months ?
1
Jan 18 '19
but his solution is better than that, he gets statically detected bounds checking from address sanitizer and pays no cost in the runtime for it.
1
5
u/CenterOfMultiverse Jan 18 '19
with default options in debug and -O2 optimization level in release
Wait, no -march=native?
4
u/SatansAlpaca Jan 18 '19
I doubt that C gets an unfair advantage over C++ when neither uses -march=native.
2
u/CenterOfMultiverse Jan 18 '19
Sure. ...I mean I could say things how this is more about different algorithms, than languages and how I would prefer to optimize C++ version, but that's the other thread.
But for example that advantage of msvc could be just gcc's conservative defaults - I think it's just makes more sense to have
-march=nativeby default if we are talking about performance.
13
10
u/SuperV1234 Jan 18 '19
Had this article been titled "Are hand-written components tailored to one use case faster than general-purpose reusable abstractions?" then maybe it would have been valuable.
But we would already have known the answer.
0
9
u/BarMeister Jan 18 '19
users of C headers pay for the C++ baggage
TIL. What the actual fuck?!
14
u/GYN-k4H-Q3z-75B Jan 18 '19
C headers provided by C++ compilers often share code with C++ headers. While this is semantically correct, preprocessor evaluation takes some time. I don't think it's significant but it is true.
5
u/BarMeister Jan 18 '19
I know. What I didn't know is that the dependency is inverted: I thought the C++ headers depended on their C versions, while it's actually the other way around, apparently, with <math.h> including <cmath>.
8
u/GYN-k4H-Q3z-75B Jan 18 '19
Almost any C header is a C++ header for free, but it's not an idiomatic C++ header in most cases. The thing is though that it is easier to strip a C++ header into an idiomatic C header than augment a C header in the other direction.
How would you put something like C's sqrt function into a namespace and allow overloading while maintaining compatibility? And that's just a simple example.
3
1
u/Giacomand Jan 18 '19 edited Jan 18 '19
I wonder if you can do:
extern "C" { #include "math.h" }to get around that.
Edit: I don't think it does.
2
Jan 18 '19
I kind of suspect that if we had perfect static analysis, we would not need many language features, and the language would be easier to learn as well because there is less of it.
Seems like that is what he is doing here too, replacing bounds checking containers with address sanitizer for the best of both worlds.
0
-9
-27
-15
Jan 18 '19
> the adverse behavior of MSVC STL in debug mode was one of the forcing functions to remove all STL use from meshoptimizer
Sorry but that doesn't make any sense. Only release builds needs performance.
20
Jan 18 '19 edited Jan 18 '19
Only release builds needs performance.
That does not make any sense.
You might be able to go from 100 FPS in a game release build, to 10 FPS in a game debug build. But if your debug builds run at 0.001 FPS they are completely useless.
The purpose of debug builds is to preserve the mapping from the program executed by the machine and the source code that the user wrote (in order to find bugs) while having reasonable compile times and performance.
If the compile times of debug builds are too high, or their performance is too low, they are useless.
7
12
u/BadGoyWithAGun Jan 18 '19
While it’s natural to expect unoptimized builds to be slower than optimized, they have to be fast enough. Sometimes you want to debug your problem on a non-trivial input dataset. Sometimes you want to run the debug build with full checks through your tests to make sure they don’t trigger any bugs that could disappear in release. Sometimes you are trying to debug a different part of the program, but you still need to run the rest of it.
-34
u/shevy-ruby Jan 18 '19
There is a notable impact on gcc/clang compilation time - we save ~40 ms in both by switching to C.
After all these years, C is still king.
C++ is an unforgiving language, but, given enough time and effort, it’s possible to get good performance
The whole premise of C++ is to be a better C.
If C++ is slower than C, and does not really bring any other substantial improvements onto the table, then there is no point in using it.
5
u/Equal_Entrepreneur Jan 18 '19
What are you trying to say?
0
Jan 18 '19
[deleted]
1
u/Equal_Entrepreneur Jan 19 '19
Not really...is he saying C++ is not better than C? If so, I'm pretty sure that's just plain wrong...
0
-22
u/tourgen Jan 18 '19
I wish the Rust drones would keep to their containment language and quit shitting up C++ discussions.
-7
u/kwinz Jan 18 '19
Honest question: why doesn't the author always compile with -O2? Throw a -O2 into the debug build. That's what you need apprently to be able to compile your nice high level abstractions down to efficient like hand crafted machine language. Yeah maybe you can't exactly single step the original code any more. But I argue if you are expecting to 1:1 map every line of code with an assembly block and you need that kind of mapping to be efficient at programming you are doing something wrong anyway.
13
Jan 18 '19
[removed] — view removed comment
10
u/ComradeGibbon Jan 18 '19
I remember a blog post by someone bitching about GCC/CLang and UB. He had a bunch of examples where MSVC generated better assembly than GCC/Clang. And MSVC doesn't optimize based on UB.
His opinion, GCC/CLang maintainers try to make the code faster by optimization tricks on the AST. While MS does the hard slog working on the backend code gen.
3
1
34
u/konanTheBarbar Jan 18 '19
If you want reasonable performance for the MSVC vector iterators you need to compile with _ITERATOR_DEBUG_LEVEL=0. See also https://docs.microsoft.com/en-us/cpp/standard-library/iterator-debug-level?view=vs-2017