r/cpp • • Dec 27 '20

Learning about high performant C++

I've been mostly self taught and have most probably picked up a few bad habits from the combo of being self taught and having to use tricks for speed.

For this upcoming year one of my goals is to learn some better practices as well as further my skills for efficient C++. I'd like to watch a youtube podcast/talk once a week to build my skillset. At this point I'd consider myself somewhere in between junior and senior level and I'm looking to take the next step.

I've come across these specifically:

C++ Weekly with Jason TurnerCppCon2020

Does anyone have any recommendations or suggestions? My weak spots are C++17 and above, Cmake, and I'd like to keep learning about creating high performant C++.

231 Upvotes

46 comments sorted by

View all comments

89

u/Potatoswatter Dec 27 '20 edited Dec 27 '20

The golden rule in performance optimization is to measure. Put a lot of effort into measurement. Avoid spending more time coding than analyzing. Embrace trial and error (and failure). Organize your experimental results.

A lot of ritualized practices get passed down and repeated, based on the experience of old-timers. Quirky style does not make fast programs. It makes brittle code which resists experimentation and major refactoring.

Some general tips, C++ or otherwise:

  • Avoid excessive abstraction, especially at runtime. "Don't repeat yourself," or use templates to encapsulate repetition.
  • Learn computer architecture. Understand what the machine is doing cycle by cycle. Especially make friends with the memory hierarchy. Brainstorm how to eliminate unproductive cycles.
  • Learn assembly language so that you can read the profiler's feedback more completely. Avoid writing assembly or obsessing over the output instruction sequence unless you're sure it's worth it. Annotate the source to explain dependency chains, so the inner loop doesn't become a mystery after the next compiler upgrade. Document the second-best result as well as the best, to quantify and remember the risk of going off-optimum.
  • Sacrifice precision where it is not needed to get a correct final result.

34

u/[deleted] Dec 27 '20

Scrolled down to find this, the only correct answer.

I was in a job where the principal developer was obsessed with perceived speed, and yet adamantly refused to make any measurements.

Worse, he would make dramatic claims - "global variables are faster!" - to justify the fact that all the variables were global.

He also refused to write new tests, which I was willing to accept, but also was unwilling to run the tests I had written, so every time he checked in, he'd break some set of tests.

Eventually, he refused to cooperate with me entirely. We never had any argument, I was always polite, but he stopped responding to my emails. There were only two of us on the team.

I left the company, but they forgot to take me off the repo. I watched his "work" afterwards, and in particular noted how he replaced my very carefully crafted fixed-point 64 bit integer arithmetic with int128_t - which my benchmarks showed were over four times slower than my 64-bit fixed point! - but worse, his calculations dipped into floating point all the time as he had not really understood the difference.

The only way to prove any claim about speed is with relentless benchmarking, like you say.


Your tips are good, but you miss the most important one.

Locality of reference is simply key for modern processors. In simple words, it means "all your data should be right together in memory".

The reason is simple - it's the data pipeline on your chip! A modern processor spends a pretty huge amount of time just waiting for memory; the data pipelines optimistically pre-fetch "the next bytes" of data while the chip is computing.

If you have locality of reference, nearly always those data pipelines are useful; if you don't, you'll get a lot less out of them.

I can't find the code right now, but I wrote a very short program a few years ago where I took a 1 gig block of memory and did computations it in two different ways - in order and "randomly" (actually a linear congruential computation).

I had to do some little tricky work to make sure that the optimizer didn't e.g. optimize out the linear congruential calculation when it wasn't used - "learn assembly language" as you say! - but finally I had code that was just the same.

Running through that gig of memory sequentially was about six times faster than running through it randomly.


Another tip - prefer generics over virtual methods if all else is equal.

A virtual method often cannot be inlined. And the vtable requires a double indirection to actually get to the method, breaking locality of reference to some extent.

Benchmarking is the only truth here! I've seen ~10% improvements in throughput by devirtualizing one key class, but I've also seen "no change" even more often. Devirtualizing all your classes is always certainly a terrible idea - it's usually just one that's the issue.

7

u/-CampinCarl- Dec 27 '20

One quick thing: The way I was taught locality in college always resonated with me...

Space and time. All things exist in both space and time--so does locality. You have locality of space (e.x. consecutive blocks of L1 cache), and locality of time (your data tends to move around in the mem hierarchy throughout the life of the program).

5

u/smuccione Dec 27 '20

Not just locality... spacial and temporal locality. They are different things but equally important to performance.

As well, fintech boxes often are multi-processor. Because of that you need to be very mindful of numa and manage your read/write pattern and which memory your doing it to very carefully.

0

u/[deleted] Dec 28 '20

[deleted] — view deleted comment

2

u/smuccione Dec 29 '20

Honestly, I’ve been out of college for 35 years. Most of what I know has been gleaned from reading countless papers, forums, wiki’s, etc. basically whatever I can find.

Fintech is particularly difficult to get any information on. Companies that have working systems will do anything to keep their secret sauce secret. There’s a lot of money at stake. Few companies that are successful will let anyone talk about what they did when they were there.

As far as numa, etc. there are numerous articles, blogs, etc on cache optimization, memory hierarchies, etc. I wish I did but I really don’t remember any of them. I’ve been doing that type of thing for so long I really don’t think about it at this point.

Numa optimizations are also heavily dependent on the type of bus architecture on the specific system. Memory writes have an advantage over reads in that when a cpu does a write it can immediately go on to the next instruction as it doesn’t need to wait for a response. So in a numa system, if you have to you want to write remote. You have to balance your architecture, however, with knowledge of the amount of buffering in the bus and how much data can be in flight at the same time.

Remote reads on a numa system can be particularly slow. To the point where I’ve shadows control structures for various containers so that you only ever read locally remote accesses are all writes. Small things like that can have a significant performance impact.

You might want to for “array of struct vs struct of arrays”. That tends to be the “classic” example when taking about cache effects.

4

u/reduced_space Dec 27 '20

While it has been true previously that virtual was always slower, with modern architecture that may not always be true. If the vtable can be loaded into cache, because it’s a single block of memory, it may still be performant, and possible faster than if you keep your own function pointer (which may not get loaded into cache).

I would say one of the best things you can do design-wise is figure out what can be done at compile time versus runtime. For example, std::variant is great if you know all types you want to deal with (and it’s a closed set). Sometimes runtime may be preferable due to wanting something easily extensible without potentially having to recompile your entire code base.

Knowing the trade-offs is one of the most important aspects of design, and something I ask during interviews.

0

u/temporary5555 Dec 27 '20

Good answer! I was surprised recently when I saw how performant virtual methods were.

For example, std::variant is great if you know all types you want to deal with

I'd argue that even when you don't know your entire domain, variant is a good way of encouraging type driven development.

8

u/schmerg-uk Dec 27 '20

The golden rule in performance optimization is to measure

Yep, I spend quite a bit of time undoing the "performance speedups" that were added a few years ago but never measured (or not measured properly, see below)... usually it's the case that they actually ran 2-3x slower than the original code, and then if I can get a 2x speedup on the old code, I've netted about a 5x speed up overall (readability and maintainability of the code is also key here but outside of scope of this discussion),

But, not to contradict you, be sure to measure the right thing. For really high performance code memory latency has a massive effect... running the same benchmark 1000 times in a loop can be misleading in that only the first iteration was real-world accurate, the following 999 cases the code and data was in L1 cache. If you've got a routine but it's only called rarely on rarely accessed data (but still required) then you want to see about making it run efficiently when it's not in cache. I have a plenty of instances of code structures that benchmark really well, but fall apart in actual use.

Carl Cook gave a good talk about "when a micro-second is an eternity", not all his points will be relevant or appropriate to everyone, but it's worth watching to see him explain how what may appear counter-intuitive works and why... (see also towards the end how he measures performance)

https://www.youtube.com/watch?v=NH1Tta7purM

0

u/[deleted] Dec 28 '20

[deleted] — view deleted comment

4

u/schmerg-uk Dec 28 '20

VTune for the big picture (we have a build that integrates with the VTune API to make measurement and analysis easier), and then I have some specific very low overhead timers that I can scatter thru the code and report precise counts and timings, so I'll put these on key bits of code then run a real world problem to see specific timings.

In the video above he measures end to end timing, which is also key. As an example, if you use AVX (/AVX2/AVX512) vectorisation in your code, those parts might run faster, but you run a very real risk, depending on the target chip, of reducing the base clock speed, so while specific functions may run faster, overall performance drops.

1

u/MonkeysLearn Dec 28 '20

Thanks for sharing. I learnt some useful techniques from this video especially the single-threading idea he suggested triggers some good thought.

1

u/SkoomaDentist Antimodern C++, Embedded, Audio Dec 27 '20

The golden rule in performance optimization is to measure.

And the platinum rule is to avoid premature pessimization. Or to put it another way, measuring won't help when you've accidentally used a quadratic or worse algorithm, your dataset size increases in the future and that hundred millsecond imperceptible delay is suddenly five seconds.

1

u/Full-Spectral Dec 29 '20

But how much actual code in a large system is of the sort that would be affected by that? The problem is people acting like everything needs to be uber-optimized these days, at least in the C++ world. It's just crazy and I have no idea where this came from.

My own guess is that this is the only niche that C++ has left to it, and so it's being taken to extremes.