Performance
Measuring and tuning C++ performance.
Measurement
Measuring so you can trust the resultWriting a microbenchmark whose results you can trust: why a naive timing loop measures 0 nanoseconds, which clock to use, how the inline asm of DoNotOptimize and ClobberMemory holds back the optimizer, warm-up, repetition and medians, sources of noise on macOS, common pitfalls, how to compare two versions fairly, and bench.hpp, the small harness shared by the rest of this section.draftperformancebenchmarkingmeasurementas-ifFinding hot spots with a profilerFind out where the time goes before optimizing: sampling vs instrumentation, building for profiling (-O2 -g, frame pointers, why -O0 profiles can't be trusted), sample, Instruments and dtrace on macOS, perf on Linux, reading call trees, flame graphs and inlined frames, what hardware counters add, and checking the gain with Amdahl's law after fixing a hot spot.draftperformanceprofilingprofilersampleReading compiler-generated assemblyThe minimum assembly knowledge needed to check what the compiler turned your C++ into: how to get the assembly, the AArch64 and x86-64 calling conventions, what common C++ constructs look like once compiled, and how to spot redundant calls, register spills and unvectorized loops in the assembly.draftperformanceassemblyAArch64x86-64
Compiler
What the compiler can and cannot do for youThe optimizer rewrites programs under the as-if rule and the assumption of no UB: what inlining, constant propagation, devirtualization, copy elision, dead store elimination and loop-invariant code motion each do; how aliasing, invisible functions, escaped addresses and volatile block them; and how to make Clang explain its decisions with -Rpass.draftperformanceoptimizationas-ifinliningAuto-vectorizationWhen the compiler rewrites a loop into SIMD instructions: the trip count must be computable, iterations must be independent, and arrays must be provably non-overlapping; why floating-point sums need the programmer's permission to reorder; how to read Clang's vectorization remarks; and what restrict, pragmas, the unseq execution policy and std::simd each tell the compiler.draftperformanceSIMDvectorizationfloating pointLink-time and profile-guided optimizationOptimization at the build level: why the compiler cannot see function bodies in another translation unit, how full LTO and ThinLTO restore inlining and devirtualization at link time and what they cost to build, PGO's instrument–merge–use steps and the code layout it changes, sampling PGO and BOLT, how much -O3 and -mcpu actually change, and two pitfalls: LTO exposing ODR violations, and stale profile data.draftperformanceLTOThinLTOPGO
Memory
Caches, locality and data layoutWhy the way you access memory often decides speed more than the amount of computation: measuring cache and memory latency on our test machine, comparing sequential, strided and random access, row-major vs column-major, linked lists vs vector, AoS vs SoA, padding caused by member order, prefetching, TLB and huge pages, and the effect of packing data into bits.draftperformancecachelocalitydata layoutMultithreaded performance: contention and false sharingWhy adding threads can make things slower: false sharing from cache lines bouncing between cores, contention when every thread updates the same atomic, which instructions each memory order produces on arm64 and what they cost, mutex vs spinlock vs atomic, reference-count contention when copying shared_ptr, and the overhead of starting threads and of thread pools, all measured on an M2 Pro with 1 to 12 threads.draftperformanceconcurrencyfalse sharingcache lineWhat heap allocation costsHow many nanoseconds one new/delete takes on our test machine, how to count allocations by replacing the global operator new, the allocations hidden in string, function, vector, node containers, shared_ptr and exceptions, when the compiler may delete a new/delete pair, and measurements of reuse, object pools, inline storage, aligned allocation and multithreaded allocation.draftperformancememory allocationoperator newSSO
Code
Avoiding unnecessary copiesUsing a counting type and timing to find the copies and moves a program can drop: how to pass parameters, when return values are elided, where range-for, structured bindings, const, emplace, map insertion and initializer_list each make an extra copy, and why small objects are faster passed by value.draftperformancecopymovecopy elisionBranches and branch predictionWhat conditional branches and indirect calls really cost on a modern CPU: how branch prediction works, how many nanoseconds a misprediction is worth, when the compiler removes a branch on its own, when branchless code wins and when it loses, and what likely/unlikely, PGO, virtual calls, switch and std::unreachable change in the assembly and in measurements.draftperformancebranch predictionassemblylikelyMoving work to compile timeWhen lookup tables, constant parameters and branches are worth computing at compile time, where the results end up in the binary, how much run time they save, and how much more you pay in compile time and size.draftperformanceconstexprconstevalconstinitChoosing containers: beyond complexityWhy containers with the same or better complexity are often slower: measurements on our test machine from 10 to 1 million elements of vector, deque and list; map, unordered_map, flat_map and sorted vector; reserve and bad hashes; small sets; heterogeneous lookup with string keys; per-element memory overhead; and, finally, why the real use of node containers is iterator and reference stability.draftperformancecontainersvectorlist