Modern C++ for scientific computing
The C++ essentials for reading and writing high-performance numerical code: the compilation model, memory and RAII, the templates behind Eigen, undefined behavior and the sanitizers that detect it, and what the compiler does (and undoes) with -O3, autovectorization and -ffast-math. Compare the same kernel in Python, NumPy and C++ on the local machine.
After this lesson you can
- Compile, link and organize a small C++ project with CMake on the local machine.
- Manage memory using value semantics, references, std::vector, std::span and RAII without leaks or dangling references.
- Write generic numerical functions with templates and use Eigen for linear algebra.
- Detect undefined behavior using AddressSanitizer and UndefinedBehaviorSanitizer.
- Read generated assembly to check whether a loop was vectorized and reason about the effect of -ffast-math.
Before you start
Motivation: the code that actually runs
When you call np.sum, torch.matmul or mujoco.mj_step, Python does almost nothing: it prepares the arguments and jumps to compiled code. NumPy’s core is written in C, with SIMD kernels in C++; ATen, PyTorch’s tensor library, in C++ and CUDA; MuJoCo is a C/C++ library with a C API; and backtesting and execution engines that must process millions of events (you will see them as an event-driven backtester) are often written in C++. Sooner or later you will need to read that code to understand why something is slow or produces a strange result, and write it when no library does what you need: your own kernel, a simulator’s inner loop, a PyTorch extension.
The difference at stake is not small. In this lesson’s lab, a Jacobi sweep over an grid costs about 100 ns per point in pure Python and around 1 ns in optimized C++: two orders of magnitude. But C++ does not hand you that speed for free. The same code compiled in debug mode is 7 to 14 times slower; one compiler option (-ffast-math) makes a Kahan sum almost thirty times faster while destroying exactly the property you wrote it for; and an out-of-bounds access can make the compiler rewrite your entire function without warning.
This lesson gives you the essentials to work there without shooting yourself in the foot:
- The compilation model: what each phase does from
.cppto the executable, what a library is and why the ABI exists, plus a minimal CMake project. - Memory: stack and heap, values, references, moves and RAII, with
std::vector,std::spanandstd::unique_ptr, and a contiguousMatrixclass. - Templates, which let you write a kernel once for
floatanddouble, and Eigen’s expression templates. - Undefined behavior, why the optimizer exploits it and how AddressSanitizer and UndefinedBehaviorSanitizer detect it.
- What the compiler does with
-O0at-O3,-march=nativeand-ffast-math, read directly in assembly.
Everything is measured on your machine: the labs compile with g++ (on Linux or WSL), and the figures use data produced by that same lab on the reference machine, an Intel Core i9-14900HX with g++ 13.3 under WSL 2.
From source to executable: the compilation model
Python reads your whole program and executes it. C++ does not: each .cpp file is compiled separately, knowing nothing about the others, and finally a different program, the linker, stitches the pieces together. Almost all bewildering C++ errors (an “undefined reference”, a “multiple definition”, a template that will not link, two libraries that do not understand each other) are direct consequences of this design.
From this come the conventions of any C++ project. Headers (.hpp) contain declarations: what other units need to know to call a function (its type), not its body. The .cpp contain the definitions. If you define a normal function in a header and include it from two .cpp files, each object gets a copy and the linker complains with “multiple definition”; if you declare it and never define it, with “undefined reference”. inline functions, those defined inside a class, and templates are exceptions: they may (and templates often must) be defined in the header, and the linker keeps one copy. #pragma once prevents a header from being expanded twice within the same unit.
The linker sees symbols, not C++ names. Because C++ allows function overloading and namespaces, the compiler mangles each name with its arguments. In the lab, nm lists what the libnumlab.a library defines; the function numlab::suma(std::span<const double>) appears as _ZN6numlab4sumaESt4spanIKdLm18446744073709551615EE: N6numlab4sumaE is the name with its namespace, St4spanIKd... the argument type, and the huge number is , the std::dynamic_extent value marking a dynamically sized span. extern "C" disables mangling and leaves the symbol with its bare name: that allows a C++ function to be called from C, from ctypes or from any other language (you will use it in the next lesson for Python extensions).
The ABI and why compilers do not mix
For an object compiled by one compiler to call another, a binary agreement is required: the ABI (application binary interface). It specifies which registers hold arguments, who cleans the stack, how classes are laid out in memory, how names are mangled and how exceptions are thrown. On Linux, gcc and clang follow the System V ABI for x86-64 and the Itanium C++ ABI, so their objects can mix. You will see this in the compiler figure’s assembly: in saxpy(float a, const float* x, float* y, std::size_t n), the scalar a arrives in xmm0 and the pointers and size in rdi, rsi and rdx. On Windows two incompatible worlds coexist: MSVC, with its own convention, name mangling and standard library, and MinGW (gcc for Windows), with those of gcc and libstdc++. An std::string or an std::vector does not have the same memory layout in both standard libraries, so a C++ interface between an MSVC DLL and a MinGW program either fails to link or, worse, links and corrupts memory. Between different worlds, the only safe boundary is a C API (extern "C", simple types and pointers).
A minimal CMake project
Nobody writes a real project’s build commands by hand. CMake describes the project in terms of targets (libraries and executables) and generates build files for Ninja, Make or Visual Studio. This is the lab’s entire CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(numlab LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(NUMLAB_NATIVE "Compilar para la CPU de esta máquina (-march=native)" OFF)
add_library(numlab STATIC src/kernels.cpp) # biblioteca estática: libnumlab.a
target_include_directories(numlab PUBLIC include)
if(NUMLAB_NATIVE)
target_compile_options(numlab PUBLIC -march=native)
endif()
add_executable(bench src/bench.cpp)
target_link_libraries(bench PRIVATE numlab) # hereda include/ y las opciones PUBLIC
PUBLIC means “for me and for whoever uses me”: bench inherits the header directory and -march=native from numlab without repeating them. Configure and build it with
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
The build type determines the flags. With gcc and clang, Debug adds only -g (that is, -O0), RelWithDebInfo uses -O2 -g -DNDEBUG and Release uses -O3 -DNDEBUG. With MSVC, Debug uses /Od and Release uses /O2. If you specify none, CMake adds no optimization: this is the most common mistake when measuring C++ performance. With the Visual Studio generator, which supports several configurations at once, the type is selected at build time: cmake --build build --config Release.
The flags used in this lesson correspond as follows:
| Purpose | gcc and clang | MSVC |
|---|---|---|
| Optimize | -O2, -O3 | /O2 |
| Instructions for this CPU | -march=native | /arch:AVX2 (no “native”) |
| Fast math | -ffast-math | /fp:fast |
| Vectorization report | -fopt-info-vec (gcc), -Rpass=loop-vectorize (clang) | /Qvec-report:2 |
| AddressSanitizer | -fsanitize=address | /fsanitize=address |
| UndefinedBehaviorSanitizer | -fsanitize=undefined | unavailable |
| Debugging information | -g | /Zi |
The labs use g++ because it covers every row, including UBSan. On Windows they run inside WSL; the CMake above also works with MSVC (removing -march=native), the compiler with which you set up the C++ toolchain.
Types and memory: stack, heap, values and references
A C++ program places its objects in two places with very different rules.
- The stack. Each function call reserves a frame with its local variables; allocating and freeing it moves a register (the stack pointer), so it costs almost nothing. Each frame’s size is known at compile time and the stack is small: 8 MiB by default for the main thread on Linux and 1 MiB on Windows. A local
double datos[10'000'000]overflows it. - The heap.
new,mallocand all containers request memory from an allocator, which finds a free block of the requested size. It is for sizes known only at runtime and objects that must outlive the function creating them. It costs a call to the allocator (tens of nanoseconds or more), and someone must return the memory.
An std::vector<double> straddles both: the object itself is three 8-byte words (pointer, size and capacity) stored wherever the variable lives, usually on the stack; the elements go in a heap block it points to.
Value semantics. In C++, a variable is its object, not a label attached to an object as in Python. std::vector<double> b = a; copies every element: afterward there are two blocks and modifying b does not affect a. To avoid copying, use references: const std::vector<double>& v is another name for a vector that exists elsewhere, passed internally as an address. A reference must be initialized and cannot switch objects; a pointer (double*) is an explicit address that can be null, change and be offset using arithmetic. const promises you will not modify the object through that name. The practical rule for arguments: pass small types (double, std::size_t, std::span) by value; large ones you only read, by const&; those you will modify, by &.
Move semantics. Copying a million-element vector to return it from a function would be absurd if the original is about to be destroyed. Since C++11, rvalue references (T&&) bind to objects nobody will use again, and move constructors steal the original’s resources instead of copying: the new vector takes the old pointer and the old vector is empty. Copying is ; moving is . std::move(a) moves nothing by itself: it is a conversion to T&& that lets you say “you may plunder a”. After std::vector<double> b = std::move(a);, the standard guarantees that a is empty (for other types, only that it is in a valid but unspecified state: you can destroy it or assign it something, nothing more). When returning a local variable (return v;), even that is unnecessary: the compiler constructs v directly in the destination (NRVO) or, if it cannot, moves it.
It is never safe to use a reference or pointer beyond the lifetime of the object it points to. The next figure walks through a program that does so without an obvious symptom.
ejemplo() line by line. On the left are stack frames with each vector's three words (pointer, size and capacity); on the right (below on a narrow screen), heap blocks. The initial state is at line 12: b.push_back does not fit, so it allocates a block twice as large, moves the elements and frees the old one, leaving reference r pointing to freed memory. Change line 11 to a copy, or make crea reserve extra capacity, and see when r survives. Advance to the end to see destructors free everything without a single handwritten delete.Three lessons from the figure. First: returning v from crea does not copy the data, and the block outlives the function that created it because ownership changes. Second: a reference to a vector element is tied to the block, not the vector; any operation that changes capacity (an push_back without room, reserve, resize, shrink_to_fit) invalidates every reference, pointer and iterator to its elements. With spare capacity r survives push_back; with the copy, r points to a’s block, which nobody touches. Third: writing through the dangling reference produces no visible error; the program carries on as if nothing happened. You will see this repeated, and detected, in the undefined-behavior gallery.
RAII and containers
Who frees the heap block? In C you handle it manually, with an free for each malloc on every exit path, including errors. C++ ties it to an object’s lifetime.
The practical consequence is the rule of zero: if your class stores resources in members that already manage themselves (std::vector, std::unique_ptr, std::string), do not write a destructor, copy or move constructor, or assignment operators: those generated by the compiler do the right thing member by member. Only a class that directly manages a raw resource needs to write all five (the rule of five), and ideally there is only one such class per resource. In modern numerical code you almost never write new or delete.
The containers and views you will use all the time:
std::vector<T>: dynamic array in one contiguous heap block. access,push_backin amortized (proved below), compatible with any API expecting a pointer and length (v.data(),v.size()).std::array<T, N>: compile-time fixed size, no heap; the elements are inside the object. Ideal for three-component vectors or matrices.std::span<T>(C++20): a non-owning view, a pointer plus length. It replaces(const double* x, std::size_t n)pairs: any contiguous container converts tospanwithout copying, and thespanfrees nothing on destruction. As a view, it must not outlive what it views.std::unique_ptr<T>: exclusive owner of a heap object. It cannot be copied, only moved, and its destructor callsdelete.std::make_unique<double[]>(n)is the right way to request a raw block.std::shared_ptrpermits multiple owners with a reference count, at the cost of atomic operations on each copy.
Proof
Moves occur only during reallocations. If the last one before reaching size occurs when the vector is full at capacity , earlier ones occurred at capacities , and each moved as many elements as the capacity. The total is bounded by the geometric series
Dividing by , each push_back costs on average one write plus fewer than moves: a constant. (The proof assumes each capacity is exactly times the previous one. With integer capacities rounded down, as MSVC does with , the effective ratio is slightly less than at some steps and the constant worsens a little, but the geometric-series argument is the same and the cost remains amortized .)
libstdc++ (gcc’s standard library) uses , as you saw in the figure going from 3 to 6: fewer than moves. MSVC’s uses : up to moves, but with less wasted memory. If you know how many elements there will be, reserve(n) avoids all reallocations and keeps references valid.
A contiguous matrix versus a vector of vectors
The “natural” way to write a dense matrix in C++, std::vector<std::vector<double>>, allocates once per row: blocks at arbitrary places on the heap, each row with its own 24-byte vector object in the outer vector and its own allocator header. The right approach is one block of elements and a function translating into index , the row-major layout from lesson 19:
template <class T>
class Matrix {
public:
Matrix(std::size_t filas, std::size_t cols, T valor = T{})
: filas_(filas), cols_(cols), datos_(filas * cols, valor) {}
T& operator()(std::size_t i, std::size_t j) { return datos_[i * cols_ + j]; }
const T& operator()(std::size_t i, std::size_t j) const { return datos_[i * cols_ + j]; }
std::size_t filas() const { return filas_; }
std::size_t cols() const { return cols_; }
std::span<T> fila(std::size_t i) { return {datos_.data() + i * cols_, cols_}; }
std::span<const T> plano() const { return datos_; } // todos los elementos, sin copia
private:
std::size_t filas_, cols_;
std::vector<T> datos_;
};
There is no destructor or copy constructor: std::vector already has them, and the rule of zero does the rest. What does the alternative actually cost? It depends on the matrix shape, and it is better to measure than repeat dogma. The next cell applies the glibc allocator model (each block occupies the requested size plus 8 header bytes, rounded to a multiple of 16 with a minimum of 32; I checked this by allocating consecutive blocks with malloc on the reference machine).
def bloque_glibc(pedido):
"""Bytes que consume un malloc(pedido) en glibc x86-64: cabecera de 8 bytes, múltiplo de 16, mínimo 32."""
return max(32, (pedido + 8 + 15) // 16 * 16)
print(f"{'columnas':>8s} {'contigua':>10s} {'vector de vectores':>19s} {'cociente':>9s}")
for m in (1, 2, 4, 8, 64, 2048):
contigua = 8 * m # bytes por fila en Matrix
vv = 24 + bloque_glibc(8 * m) # objeto vector en el exterior + su bloque
print(f"{m:8d} {contigua:10d} {vv:19d} {vv / contigua:9.2f}")With long rows the overhead is negligible (0.2% with 2048 columns), and in the lab a Jacobi sweep over takes virtually the same time with both representations: the allocator ends up placing the 16 KiB rows almost consecutively and the inner loop traverses each contiguously. With short rows the model predicts more than twice the bytes per useful element (2.25 with 4 columns), but the stopwatch does not always show it: in the lab verification run, summing rows of 4 columns cost 0.78 ns per element versus 0.72 with Matrix, only 8% more. The reason is that the ordered sum is limited by the latency of the dependent addition chain (in the lab, summing 128 MiB in Release costs almost the same per element, 0.71 ns), hiding the extra memory traffic. Construction does pay the price: 98.9 ms versus 25.3, almost 4 times more, because there are two million allocator calls. A bandwidth-bound kernel (a vectorized sum, a copy) would have to move those extra bytes. And one cost does not appear on any stopwatch: an vector<vector> cannot be passed to BLAS, LAPACK, NumPy or the GPU without first copying it into a contiguous block, whereas Matrix provides its data() directly.
Templates: generic numerical code
You want Kahan summation for float and double, and perhaps an extended-precision type. Writing it three times invites the copies to diverge. A template is a recipe the compiler fills in with the concrete type:
template <std::floating_point T>
T suma_kahan(std::span<const T> x) {
T s = 0, c = 0;
for (T v : x) { T y = v - c; T t = s + y; c = (t - s) - y; s = t; }
return s;
}
This has three consequences. First: because an instance is generated where it is used, the template body must be visible in that translation unit, so templates are defined in headers (if you define a template in one .cpp and use it from another, you get an “undefined reference”). Second: each instance is distinct code; in the lab, nm shows suma_kahan<float> and suma_kahan<double> as two symbols, marked W (weak) so the linker keeps one copy if several units instantiate the same thing. Third: more instances mean longer compilation and larger binaries. Unlike the dynamic alternative (virtual functions selecting at runtime), templates decide everything at compile time, so the optimizer can inline and vectorize across them.
Eigen and expression templates
Eigen is the leading dense linear algebra library in C++ (used by Ceres Solver and TensorFlow, among others), and consists only of headers: everything is a template. It offers fixed-size matrices (Eigen::Matrix3d, no heap, ideal for geometry) and dynamic matrices (Eigen::MatrixXd, Eigen::VectorXd), factorizations (A.partialPivLu().solve(b), A.llt(), A.householderQr()), and an idea at the heart of its performance: expression templates.
In NumPy, d = a + b + c first computes a + b into a temporary array and then adds c: two passes and a temporary, which you counted as array-expression traffic in the previous lesson. In Eigen, a + b computes nothing: it returns a small object of type CwiseBinaryOp<scalar_sum_op, ...> remembering “the sum of a and b”. Adding c produces another object nesting the first. Only when assigning to d is a single loop generated by instantiation to compute d[i] = a[i] + b[i] + c[i]: one pass and no temporary. The lab demonstrates this with the compiler itself: the type of a + b + c is a nested CwiseBinaryOp, the object occupies 48 bytes (references to operands, not the 32 MiB of data), and with the Eigen assignment was about seven times faster (3.9 ms versus 28.7 in the verification run) than the version with std::vector and an operator+ returning new vectors. That is much more than the number of memory passes explains, and the most likely cause lies in the allocator: each + in the naive version allocates 32 new MiB, and glibc requests such a large block directly from the OS with mmap, which provides untouched pages; each first write to a page causes a page fault and the kernel must zero it.
Eigen documents two traps of lazy evaluation. auto x = a + b; stores an expression, not a vector: it is evaluated whenever used and dangles if its operands were temporaries. With Eigen, declare the type (Eigen::VectorXd x = a + b;) or call .eval(). And in a product C = A * B Eigen first evaluates into a temporary in case C appears on the right (A = A * B would be incorrect if calculated in place); if you know there is no overlap, C.noalias() = A * B saves the temporary.
The next cell builds a toy Python version of the same idea, so you can see the mechanics without noise.
import numpy as np
class Expr:
"""Un nodo que recuerda una operación elemento a elemento sin calcularla."""
def __add__(self, otro):
return Suma(self, otro)
def tipo(self):
return type(self).__name__
class Vec(Expr):
def __init__(self, datos):
self.datos = np.asarray(datos, dtype=float)
def __len__(self):
return len(self.datos)
def en(self, i):
return self.datos[i]
def tipo(self):
return "Vec"
class Suma(Expr):
def __init__(self, a, b):
self.a, self.b = a, b
def __len__(self):
return len(self.a)
def en(self, i): # el valor i-ésimo se calcula bajo demanda
return self.a.en(i) + self.b.en(i)
def tipo(self):
return f"Suma<{self.a.tipo()}, {self.b.tipo()}>"
def asigna(destino, expr):
"""La única pasada: aquí se 'instancia' el bucle fusionado."""
for i in range(len(expr)):
destino[i] = expr.en(i)
a, b, c = Vec([1, 2, 3]), Vec([10, 20, 30]), Vec([100, 200, 300])
e = a + b + c
print("tipo de a + b + c:", e.tipo())
d = np.empty(3)
asigna(d, e)
print("d =", d, " (una pasada y ningún array temporal)")In C++ the decisive difference is that en(i) is not a dynamic call: the type Suma<Suma<Vec, Vec>, Vec> is known at compile time, everything is inlined and the resulting loop is the same vectorized loop you would write by hand.
Undefined behavior
The C++ standard classifies what is not fully determined into three categories. Implementation-defined behavior is decided and documented by each compiler (how many bytes an long has). Unspecified behavior allows several possibilities without requiring documentation of which (the order in which function arguments are evaluated). Undefined behavior (UB) is literally behavior for which the standard “imposes no requirements”. A program that executes it has no meaning: anything it does, including working, conforms.
Classic sources in numerical code:
- Signed overflow.
intexceeding . Unsigned integers, by contrast, are defined as arithmetic modulo or . - Out-of-bounds access to an array, an
std::vector(withoperator[]) or a pointer. - Use after free: a reference, pointer or iterator to an object whose lifetime ended, like
rin the stack figure. - Strict aliasing violation: reading an object through a pointer to another type (an
floatsuch asint*), exceptchar,unsigned charandstd::byte. - Reading an uninitialized variable, dereferencing a null pointer, shifting an integer by more bits than it has, or a data race between threads (covered in the parallelism lesson).
Why does the compiler not simply do “what the machine does”? Because UB is a contract: the programmer promises it does not occur and, in exchange, the optimizer may reason as if that were true. That promise is valuable. In for (int i = 0; i <= n; ++i) s += x[i]; (with int n), since i cannot overflow, the compiler knows the loop performs exactly iterations and i increases one by one without jumps, so it can replace i with a 64-bit pointer advancing 4 bytes, calculate the iteration count in advance and vectorize. Without the promise it would have to consider n == INT_MAX, in which i would wrap to negative and the loop would never terminate. The price is that, when the promise is broken, the optimizer does not produce “a strange value”: it produces a program reasoned from false premises.
All four cases share the fact that the -O0 result is not “the correct one”; it is simply what comes from translating the program without reasoning about it. Overflow turns a 31-iteration loop into an infinite one, because if i > 0 and 2i does not overflow, 2i > 0, so the condition can never fail. The out-of-bounds read makes esta_en_tabla(42) answer yes: since a correct program never reads tabla[4], the loop must exit earlier through return true, and the only way for that to hold for every v is always to return true. UB affects the whole execution, including what happens before the offending line. Use after free is most treacherous because nothing visible changes: with -O0 and -O2 it prints primero = 10, v[0] = 1. Strict aliasing makes f return the constant 1 it just stored without rereading memory overwritten by float.
Sanitizers: instrumentation to see errors
The cost is moderate for what they provide: Serebryany and coauthors, who designed ASan at Google, measured an average slowdown of 73% on the SPEC CPU2006 suite. They are therefore used in tests, continuous integration and short debugging training runs, not production. In the gallery, ASan flags the overflow of tabla and the write to a freed block (with the stack of operator delete that freed it: the reallocation of push_back), and UBSan flags 1073741824 * 2 that does not fit in int. Notice the fourth row: no gcc sanitizer detects strict aliasing, and the instrumented binary, compiled with -O1, does not even reproduce the failure. The safeguard is to avoid the pattern: std::bit_cast (C++20) or std::memcpy to reinterpret bits, or -fno-strict-aliasing in legacy code.
These errors are not only a correctness problem. Writing or reading outside a block, or in a freed one, is a classic route for malicious input to take control of a program: the Chromium security team estimates that around 70% of its high-severity security bugs are memory-safety problems in C and C++. Defenses therefore come in layers: abstractions that know their bounds (std::span, std::vector::at, std::string instead of raw arrays), optional standard-library bounds checks (-D_GLIBCXX_ASSERTIONS in libstdc++), compiler protections (-fstack-protector-strong, -D_FORTIFY_SOURCE=2), and sanitizers combined with tests and fuzzing in continuous integration. The same attack-surface reasoning appears for machine-learning systems in the ML attack surface: all native code processing external data (model-format readers, image readers, tokenizers) is part of it.
What the compiler does with your loop
With -O0, gcc translates each expression separately and stores each variable on the stack after every statement so the debugger can inspect it. It is the most faithful translation and the slowest. Higher levels chain hundreds of transformations.
To vectorize a loop, the compiler must prove three things: the number of iterations can be calculated on entry, no iteration depends on another (except reductions it can reorganize), and writes do not overwrite data read by other iterations. With pointers, the last condition can almost never be proved at compile time: y could point inside x. gcc solves this by versioning: it checks at runtime whether ranges overlap and chooses the vector or scalar version. __restrict (a compiler extension; in C the keyword is restrict) is your promise that they do not overlap, and eliminates the check. Breaking that promise is, again, undefined behavior.
How do you know what happened? Ask the compiler (-fopt-info-vec-optimized and -fopt-info-vec-missed in gcc, -Rpass=loop-vectorize in clang, /Qvec-report:2 in MSVC) and, above all, read the assembly (-S -masm=intel), locally or in Compiler Explorer (godbolt.org), where you see machine code from any compiler as you write. The next figure is your pocket Compiler Explorer: five kernels compiled with five sets of flags, with their assembly, vectorization report and measured times.
What the figure’s data show, kernel by kernel:
- saxpy. From
-O0to-O2the time per element in L1 falls from 1.20 to 0.27 ns without a single vector instruction: simply by removing trips to and from the stack.-O3vectorizes with SSE (xmmregisters, 4floatper instruction) and drops to 0.085 ns;-march=nativeswitches to AVX2 (ymmregisters, 8float) with one FMA per 8 elements and reaches 0.039 ns, 31 times less than-O0. With data in RAM, however, all vector versions take the same time, between 0.36 and 0.43 ns: the core waits for memory, and the roofline model says no wider instruction will fix that. Before the vector loop is an overlap check; with__restrictit disappears, and time barely changes because it is one check per call, not per element. - sum. Here is the surprise. At
-O3the report says loop vectorized using 16 byte vectors and the time is that of-O2(0.52 ns): the hot loop is four chained scalaraddssinstructions, and with-march=native, eightvaddss. gcc has made an ordered reduction: it reads 4 or 8 at a time, but adds in exact source order because floating-point addition is not associative and reordering changes the result. The report tells you what it attempted; the assembly, what happens. Only with-ffast-mathdoes onevaddps ymmper iteration appear (8 additions in parallel in 8 accumulators), dropping time to 0.074 ns, seven times less. - Kahan. Without
-ffast-mathit is not vectorized (unsupported use in stmt:sis used to computec, so it is not a simple reduction) and costs 2.2 ns per element because each iteration chains four dependent operations. With-ffast-mathit costs 0.075 ns, 29 times less, and its assembly is identical tosuma: relative error changes from to . The next section explains what happened. - Branching loop. Leaky ReLU is not vectorized without
-ffast-math(control flow in loop). Turning the branch into a selection requires computing0.01f * x[i]even whenx[i] > 0, and by default gcc respects that this multiplication might raise a floating-point exception the original does not raise (-ftrapping-math);-fno-trapping-mathis enough to vectorize it. Branch cost depends on the data: with M random signs, the scalar version takes about 4.3 ns per element, and the same function with allxpositive takes about 0.5 ns. Since code and memory traffic are the same, the difference is the price of branch mispredictions. With it costs 0.8 to 1 ns: the same sign pattern repeats in each of the thousands of measured calls, and the predictor, which decides from recent branch history, most likely learns much of it. The vector version has no branches to mispredict: 0.07 ns in L1.
ymm register has 256 bits. How many float values (IEEE 754 binary32) does a vector instruction such as vaddps ymm0, ymm0, ymm1 process?-ffast-math: when the compiler stops respecting IEEE 754
-ffast-math is not a switch but a package. In gcc it enables -fno-math-errno, -funsafe-math-optimizations (which itself includes -fassociative-math, -freciprocal-math, -fno-signed-zeros and -fno-trapping-math), -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans, -fcx-limited-range and -fexcess-precision=fast. Each part allows the compiler to treat floating-point numbers as if they were real numbers, giving up an IEEE 754 guarantee:
- Reassociate (
-fassociative-math): and become interchangeable. This allows splitting a sum among 8 accumulators and vectorizing it. The result changes, sometimes for the better and sometimes worse, and depends on register width and unrolling: it ceases to be reproducible across flags and machines. - Assume no NaNs or infinities (
-ffinite-math-only):std::isnan(x)compiles asfalse. - Ignore the sign of zero and invert divisions:
x / ycan becomex * (1 / y), which does not always agree in the last bit.
Why Kahan compensation disappears
Compensated summation works because, in floating-point arithmetic, loses the low bits of , and recovers them with the sign reversed. But over the real numbers
identically. A compiler allowed to reassociate makes exactly that simplification: is always 0, the line float y = x[i] - c reduces to y = x[i], and what remains is naive summation, which it can now vectorize. That is what the figure shows: the assembly of kahan with -ffast-math is that of suma and its relative error, , is the same. It is not even that of naive ordered summation (): it is that of 8 naive sums in parallel, which accumulate less error because each accumulator is smaller. Kahan, without -ffast-math, gives : the final rounding of the exact result to float.
The cell reproduces the three behaviors in NumPy with float32 and an explicit model of each compilation: ordered summation (what -O3 does), eight accumulators combined at the end (what -ffast-math does with AVX2), and ordered Kahan.
import math
import numpy as np
import sympy as sp
def kahan32(xs):
s = c = np.float32(0.0)
for v in xs:
y = v - c
t = s + y
c = (t - s) - y
s = t
return s
def en_orden(x): # cumsum en float32 es secuencial: el bucle de -O3
return np.cumsum(x, dtype=np.float32)[-1]
def ocho_carriles(x): # 8 acumuladores, uno por carril de un ymm, y la suma final
c = np.cumsum(x.reshape(-1, 8), axis=0, dtype=np.float32)[-1]
return np.float32(c[:4] + c[4:]).sum(dtype=np.float32)
rng = np.random.default_rng(42)
n, repeticiones = 1 << 16, 12
errores = {"en orden (-O3)": [], "8 carriles (-ffast-math)": [], "Kahan (-O3)": []}
for _ in range(repeticiones):
x = rng.random(n, dtype=np.float32)
exacta = math.fsum(x.tolist()) # suma correctamente redondeada de los float32 guardados
for nombre, f in zip(errores, (en_orden, ocho_carriles, kahan32)):
errores[nombre].append(abs(float(f(x)) - exacta) / exacta)
print(f"Error relativo de sumar {n} uniformes en float32 (mediana y máximo de {repeticiones} sumas):")
for nombre, e in errores.items():
print(f" {nombre:26s} mediana {np.median(e):.1e} máximo {max(e):.1e}")
s, y = sp.symbols("s y", real=True)
print("\nEn los reales, c = ((s + y) - s) - y se simplifica a:", sp.simplify(((s + y) - s) - y))At the median, the three errors rank as in C++: ordered summation is worst, eight lanes improve by about an order of magnitude, and Kahan is at the rounding of the result. Several sums are needed to establish this: in one, ordered summation may be lucky and come below eight lanes because rounding errors partially cancel. sympy performs the algebra gcc does.
-ffast-math also has effects beyond your loop. The local lab cell shows this with two three-line programs: std::isnan(x) compiles as xor eax, eax, that is, return false, so any NaN detection in your code (such as tracing NaNs and infinities in training) silently disappears; and linking with -ffast-math, even if the code was compiled without it, makes gcc add crtfastmath.o, which at startup enables CPU modes that turn subnormals into zero for the entire process, including libraries that requested nothing. On the reference machine, 1e-310 * 1 prints 1e-310 without the option and 0 with it, whether compiled or only linked with -ffast-math.
If a reduction matters for performance, there are ways to request reassociation only where you want it: write several accumulators yourself (the result is fixed by your code, not the flags), compile that translation unit separately with -fassociative-math -fno-signed-zeros -fno-trapping-math, or annotate the loop with #pragma omp simd reduction(+:s) (with -fopenmp-simd), which permits reordering that sum and nothing else.
Lab 1: from a Python loop to a C++ loop
This lab runs on your machine (runtime=local) and needs g++ and, if available, CMake. On Linux it uses them directly; on Windows, through WSL (sudo apt install build-essential cmake inside Ubuntu). The first cell locates the toolchain and defines two utilities used by the rest: sh, which runs a shell command in the compilation environment, and escribe, which creates project files in the cpp_lab folder.
import json, platform, re, shlex, shutil, subprocess
from pathlib import Path
LAB = Path("cpp_lab").resolve()
LAB.mkdir(exist_ok=True)
def _ruta_wsl(p):
"""C:\\a\\b -> /mnt/c/a/b, para pasar rutas de Windows a WSL."""
p = str(Path(p).resolve())
return "/mnt/" + p[0].lower() + p[2:].replace("\\", "/")
def _hay_gpp_en_wsl():
try:
r = subprocess.run(["wsl", "-e", "bash", "-c", "command -v g++"], capture_output=True, timeout=60)
return r.returncode == 0
except Exception:
return False
if platform.system() != "Windows" and shutil.which("bash") and (shutil.which("g++") or shutil.which("clang++")):
MODO = "nativo"
elif platform.system() == "Windows" and shutil.which("wsl") and _hay_gpp_en_wsl():
MODO = "wsl"
else:
MODO = None
def sh(orden, cwd=LAB, timeout=600):
"""Ejecuta una orden de shell POSIX en el entorno de compilación (Linux, macOS o WSL)."""
if MODO is None:
raise RuntimeError("No hay g++ o clang++: instala build-essential en Linux o WSL (m00, lección 1).")
if MODO == "wsl":
args = ["wsl", "-e", "bash", "-c", f"cd {shlex.quote(_ruta_wsl(cwd))} && {orden}"]
else:
args = ["bash", "-c", orden]
return subprocess.run(args, cwd=cwd, capture_output=True, text=True,
encoding="utf-8", errors="replace", timeout=timeout)
def escribe(ruta, texto):
ruta = LAB / ruta
ruta.parent.mkdir(parents=True, exist_ok=True)
ruta.write_text(texto, encoding="utf-8", newline="\n")
if MODO:
r = sh("g++ --version | head -1; (command -v cmake >/dev/null && cmake --version | head -1) || echo 'cmake: no instalado'; "
"grep -m1 'model name' /proc/cpuinfo | cut -d: -f2; "
"grep -o -w -E 'avx2|fma|avx512f' /proc/cpuinfo | sort -u | tr '\\n' ' '")
print(f"Compilación en: {MODO}\n{r.stdout.strip()}")
else:
print("No se ha encontrado g++ ni clang++ (ni en WSL). Instálalo y vuelve a ejecutar.")npm run lab and open the connection link.A project with a library and benchmark
The next cell writes the complete project: the Matrix header, the kernels header, a static library with a reduction, a Jacobi sweep (with Matrix and vector<vector>) and accelerations for bodies, and a measurement program. It builds it with CMake in five configurations and runs each. The methodology follows benchmarking: the same inputs in every variant, the best of several repetitions, sizes that do not fit in cache for memory-bound kernels, time per unit of work (element, point or interaction) to compare different sizes, and a checksum that prevents the compiler from removing work and verifies all versions compute the same result.
escribe("proyecto/CMakeLists.txt", r'''cmake_minimum_required(VERSION 3.20)
project(numlab LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(NUMLAB_NATIVE "Compilar para la CPU de esta máquina (-march=native)" OFF)
add_library(numlab STATIC src/kernels.cpp) # biblioteca estática: libnumlab.a
target_include_directories(numlab PUBLIC include)
if(NUMLAB_NATIVE)
target_compile_options(numlab PUBLIC -march=native)
endif()
add_executable(bench src/bench.cpp)
target_link_libraries(bench PRIVATE numlab) # hereda include/ y las opciones PUBLIC
''')
escribe("proyecto/include/numlab/matrix.hpp", r'''#pragma once
#include <cstddef>
#include <span>
#include <vector>
namespace numlab {
// Matriz densa en un único bloque contiguo, por filas. Regla del cero: copiar, mover y
// destruir los genera el compilador a partir de std::vector, que ya gestiona la memoria.
template <class T>
class Matrix {
public:
Matrix(std::size_t filas, std::size_t cols, T valor = T{})
: filas_(filas), cols_(cols), datos_(filas * cols, valor) {}
T& operator()(std::size_t i, std::size_t j) { return datos_[i * cols_ + j]; }
const T& operator()(std::size_t i, std::size_t j) const { return datos_[i * cols_ + j]; }
std::size_t filas() const { return filas_; }
std::size_t cols() const { return cols_; }
std::span<T> fila(std::size_t i) { return {datos_.data() + i * cols_, cols_}; }
std::span<const T> fila(std::size_t i) const { return {datos_.data() + i * cols_, cols_}; }
std::span<const T> plano() const { return datos_; } // todos los elementos, sin copia
private:
std::size_t filas_, cols_;
std::vector<T> datos_;
};
} // namespace numlab
''')
escribe("proyecto/include/numlab/kernels.hpp", r'''#pragma once
#include <span>
#include <vector>
#include "numlab/matrix.hpp"
namespace numlab {
double suma(std::span<const double> x);
void jacobi(const Matrix<double>& u, Matrix<double>& v);
void jacobi_vv(const std::vector<std::vector<double>>& u, std::vector<std::vector<double>>& v);
void aceleraciones(std::span<const double> x, std::span<const double> y, std::span<const double> z,
std::span<const double> m, std::span<double> ax, std::span<double> ay,
std::span<double> az, double eps2);
}
''')
escribe("proyecto/src/kernels.cpp", r'''#include "numlab/kernels.hpp"
#include <cmath>
namespace numlab {
double suma(std::span<const double> x) {
double s = 0.0;
for (double v : x) s += v;
return s;
}
// Un barrido de Jacobi para la ecuación de Laplace: media de los cuatro vecinos.
void jacobi(const Matrix<double>& u, Matrix<double>& v) {
const std::size_t n = u.filas(), m = u.cols();
for (std::size_t i = 1; i + 1 < n; ++i)
for (std::size_t j = 1; j + 1 < m; ++j)
v(i, j) = 0.25 * (u(i - 1, j) + u(i + 1, j) + u(i, j - 1) + u(i, j + 1));
}
void jacobi_vv(const std::vector<std::vector<double>>& u, std::vector<std::vector<double>>& v) {
const std::size_t n = u.size(), m = u[0].size();
for (std::size_t i = 1; i + 1 < n; ++i)
for (std::size_t j = 1; j + 1 < m; ++j)
v[i][j] = 0.25 * (u[i - 1][j] + u[i + 1][j] + u[i][j - 1] + u[i][j + 1]);
}
// Aceleración gravitatoria (G = 1) con suavizado eps2, en estructura de arrays (SoA).
void aceleraciones(std::span<const double> x, std::span<const double> y, std::span<const double> z,
std::span<const double> m, std::span<double> ax, std::span<double> ay,
std::span<double> az, double eps2) {
const std::size_t n = x.size();
for (std::size_t i = 0; i < n; ++i) {
double sx = 0.0, sy = 0.0, sz = 0.0;
for (std::size_t j = 0; j < n; ++j) {
double dx = x[j] - x[i], dy = y[j] - y[i], dz = z[j] - z[i];
double r2 = dx * dx + dy * dy + dz * dz + eps2;
double inv = 1.0 / std::sqrt(r2);
double s = m[j] * inv * inv * inv;
sx += s * dx; sy += s * dy; sz += s * dz;
}
ax[i] = sx; ay[i] = sy; az[i] = sz;
}
}
} // namespace numlab
''')
escribe("proyecto/src/bench.cpp", r'''#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <vector>
#include "numlab/kernels.hpp"
using numlab::Matrix;
template <class F> double mejor_s(F f, int rep) { // mejor de rep ejecuciones, en segundos
double mejor = 1e300;
for (int r = 0; r < rep; ++r) {
auto t0 = std::chrono::steady_clock::now();
f();
mejor = std::min(mejor, std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
}
return mejor;
}
int main() {
// reducción: 2^24 doubles (128 MiB, no cabe en caché)
const std::size_t nr = std::size_t(1) << 24;
std::vector<double> r(nr);
for (std::size_t k = 0; k < nr; ++k) r[k] = std::sin(1e-3 * double(k));
double s = 0;
double t = mejor_s([&] { s = numlab::suma(r); }, 5);
std::printf("suma %.4f %.3f %.3f %.10e\n", t * 1e9 / nr, nr / t * 1e-9, 8.0 * nr / t * 1e-9, s);
std::vector<double> w(nr); // techo de memoria: copiar lee 8 y escribe 8 bytes
t = mejor_s([&] { std::copy(r.begin(), r.end(), w.begin()); }, 5);
std::printf("copia %.4f 0 %.3f %.10e\n", t * 1e9 / nr, 16.0 * nr / t * 1e-9, w[nr / 2]);
// stencil: rejilla 2048 x 2048 (32 MiB por matriz)
const std::size_t n = 2048, pts = (n - 2) * (n - 2);
Matrix<double> u(n, n), v(n, n);
std::vector<std::vector<double>> uu(n, std::vector<double>(n)), vv(n, std::vector<double>(n));
for (std::size_t i = 0; i < n; ++i)
for (std::size_t j = 0; j < n; ++j) uu[i][j] = u(i, j) = std::sin(0.01 * double(i)) * std::cos(0.02 * double(j));
t = mejor_s([&] { numlab::jacobi(u, v); }, 7);
double cs = 0;
for (double q : v.plano()) cs += q;
std::printf("jacobi %.4f %.3f %.3f %.10e\n", t * 1e9 / pts, 4.0 * pts / t * 1e-9, 16.0 * pts / t * 1e-9, cs);
t = mejor_s([&] { numlab::jacobi_vv(uu, vv); }, 7);
cs = 0;
for (auto& f : vv) for (double q : f) cs += q;
std::printf("jacobi_vv %.4f %.3f %.3f %.10e\n", t * 1e9 / pts, 4.0 * pts / t * 1e-9, 16.0 * pts / t * 1e-9, cs);
// filas cortas: 2^21 filas de 4 columnas, construir y sumar todo
const std::size_t fc = std::size_t(1) << 21, cc = 4;
double sc = 0, svv = 0;
double tb_c = mejor_s([&] { Matrix<double> a(fc, cc, 1.0); sc = a(fc - 1, cc - 1); }, 3);
double tb_v = mejor_s([&] { std::vector<std::vector<double>> a(fc, std::vector<double>(cc, 1.0)); svv = a[fc - 1][cc - 1]; }, 3);
Matrix<double> ac(fc, cc, 1.0);
std::vector<std::vector<double>> av(fc, std::vector<double>(cc, 1.0));
double ts_c = mejor_s([&] { sc = numlab::suma(ac.plano()); }, 7);
double ts_v = mejor_s([&] { svv = 0; for (auto& f : av) for (double q : f) svv += q; }, 7);
std::printf("cortas %.4f %.4f %.4f %.4f %.1f %.1f\n", ts_c * 1e9 / (fc * cc), ts_v * 1e9 / (fc * cc),
tb_c * 1e3, tb_v * 1e3, sc, svv);
// N cuerpos: 2048 cuerpos, 2048^2 interacciones de 20 flops
const std::size_t nb = 2048;
std::vector<double> x(nb), y(nb), z(nb), m(nb), ax(nb), ay(nb), az(nb);
for (std::size_t k = 0; k < nb; ++k) {
x[k] = std::cos(0.7 * double(k)); y[k] = std::sin(1.3 * double(k)); z[k] = std::cos(2.9 * double(k) + 1.0);
m[k] = 1.0 / double(nb);
}
t = mejor_s([&] { numlab::aceleraciones(x, y, z, m, ax, ay, az, 1e-4); }, 5);
double ca = 0;
for (std::size_t k = 0; k < nb; ++k) ca += std::fabs(ax[k]) + std::fabs(ay[k]) + std::fabs(az[k]);
double pares = double(nb) * double(nb);
std::printf("nbody %.4f %.3f 0 %.10e\n", t * 1e9 / pares, 20.0 * pares / t * 1e-9, ca);
}
''')
# Configuraciones de CMake: Debug es -O0 (solo -g), RelWithDebInfo -O2 y Release -O3.
CONFIGS = [("Debug (-O0)", "Debug", False, ""), ("RelWithDebInfo (-O2)", "RelWithDebInfo", False, ""),
("Release (-O3)", "Release", False, ""), ("Release + native", "Release", True, ""),
("native + fast-math", "Release", True, "-ffast-math")]
P = LAB / "proyecto"
tiene_cmake = sh("command -v cmake").returncode == 0
res_cpp = {}
for k, (nombre, tipo, nativo, extra) in enumerate(CONFIGS):
b = f"build{k}"
if tiene_cmake:
r = sh(f"cmake -S . -B {b} -DCMAKE_BUILD_TYPE={tipo} -DNUMLAB_NATIVE={'ON' if nativo else 'OFF'} "
f"-DCMAKE_CXX_FLAGS='{extra}' > /dev/null && cmake --build {b} -j 4 > /dev/null", cwd=P)
else: # lo mismo a mano: compilar cada unidad de traducción, archivar y enlazar
fl = {"Debug": "-g", "RelWithDebInfo": "-O2 -g -DNDEBUG", "Release": "-O3 -DNDEBUG"}[tipo]
fl += (" -march=native" if nativo else "") + " " + extra
r = sh(f"mkdir -p {b} && g++ -std=c++20 {fl} -Iinclude -c src/kernels.cpp -o {b}/kernels.o && "
f"ar rcs {b}/libnumlab.a {b}/kernels.o && g++ -std=c++20 {fl} -Iinclude src/bench.cpp "
f"{b}/libnumlab.a -o {b}/bench", cwd=P)
assert r.returncode == 0, r.stderr[-1500:]
salida = sh(f"./{b}/bench", cwd=P).stdout
res_cpp[nombre] = {l.split()[0]: [float(v) for v in l.split()[1:]] for l in salida.splitlines()}
r = sh("nm build2/libnumlab.a | grep ' T ' | grep suma; nm -C build2/libnumlab.a | grep ' T ' | grep -E 'suma|jacobi\\('", cwd=P)
print("Símbolos que define libnumlab.a (nm, primero tal cual y después descodificados con -C):\n" + r.stdout)
print(f"Compilado con {'CMake' if tiene_cmake else 'g++ directamente (no hay CMake)'}. "
"ns por elemento (suma), por punto (Jacobi) o por interacción (N cuerpos), y GFLOP/s:")
print(f" {'configuración':22s}{'suma':>16s}{'Jacobi':>16s}{'N cuerpos':>17s}")
for nombre, d in res_cpp.items():
print(f" {nombre:22s}" + "".join(f"{d[k][0]:8.3f} ({d[k][1]:5.2f})" for k in ("suma", "jacobi", "nbody")))
c = res_cpp["Release (-O3)"]
print(f"\nMatrix contigua frente a vector<vector<double>>, en Release (-O3):")
print(f" Jacobi 2048 x 2048: {c['jacobi'][0]:.3f} frente a {c['jacobi_vv'][0]:.3f} ns por punto")
print(f" 2^21 filas de 4: sumar {c['cortas'][0]:.3f} frente a {c['cortas'][1]:.3f} ns por elemento; "
f"construir {c['cortas'][2]:.1f} frente a {c['cortas'][3]:.1f} ms")
print(f"Comprobación (deben coincidir entre configuraciones salvo redondeo): suma {c['suma'][3]:.6e}, "
f"Jacobi {c['jacobi'][3]:.6e}, N cuerpos {c['nbody'][3]:.6e}")
# Qué bucles dice gcc que ha vectorizado, con y sin -ffast-math (el informe, no el ensamblador)
fuente = (P / "src" / "kernels.cpp").read_text(encoding="utf-8").splitlines()
for extra in ("", "-ffast-math"):
r = sh(f"g++ -std=c++20 -O3 -march=native {extra} -Iinclude -fopt-info-vec-optimized -c src/kernels.cpp -o /dev/null", cwd=P)
lineas = sorted({int(q) for q in re.findall(r"kernels\.cpp:(\d+):\d+: optimized: loop vectorized", r.stderr)})
print(f"\nBucles que el informe da por vectorizados con -O3 -march=native {extra}:")
for q in lineas:
print(f" línea {q:2d}: {fuente[q - 1].strip()}")npm run lab and open the connection link.Now the same in pure Python and NumPy, with the same inputs. Pure Python is measured with smaller sizes (cost per unit of work does not depend on size), NumPy with the same sizes as C++. The cell also compares results with C++ and places memory-bound kernels under the roofline ceiling, using the best bandwidth measured by the 128 MiB copy.
import time
import numpy as np
def mejor_s(f, rep=3):
ts = []
for _ in range(rep):
t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
return min(ts)
# --- mismas entradas que bench.cpp ---
r = np.sin(1e-3 * np.arange(1 << 24))
n = 2048
i, j = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")
u = np.sin(0.01 * i) * np.cos(0.02 * j)
nb = 2048
k = np.arange(nb)
x, y, z = np.cos(0.7 * k), np.sin(1.3 * k), np.cos(2.9 * k + 1.0)
m = np.full(nb, 1.0 / nb)
eps2 = 1e-4
def jacobi_np(u):
v = np.zeros_like(u)
v[1:-1, 1:-1] = 0.25 * (u[:-2, 1:-1] + u[2:, 1:-1] + u[1:-1, :-2] + u[1:-1, 2:])
return v
def acel_np(x, y, z, m):
dx, dy, dz = x[None, :] - x[:, None], y[None, :] - y[:, None], z[None, :] - z[:, None]
inv = 1.0 / np.sqrt(dx * dx + dy * dy + dz * dz + eps2)
s = m[None, :] * inv * inv * inv
return (s * dx).sum(1), (s * dy).sum(1), (s * dz).sum(1)
# --- Python puro, con tamaños menores (el coste por unidad no depende del tamaño) ---
rl = r[: 1 << 20].tolist()
def suma_py(xs):
s = 0.0
for v in xs:
s += v
return s
nl = 256
ul = u[:nl, :nl].tolist()
def jacobi_py(u):
n = len(u)
v = [[0.0] * n for _ in range(n)]
for a in range(1, n - 1):
for b in range(1, n - 1):
v[a][b] = 0.25 * (u[a - 1][b] + u[a + 1][b] + u[a][b - 1] + u[a][b + 1])
return v
npy = 256
xl, yl, zl, ml = (q[:npy].tolist() for q in (x, y, z, m))
def acel_py(x, y, z, m):
n = len(x); ax = [0.0] * n; ay = [0.0] * n; az = [0.0] * n
for a in range(n):
sx = sy = sz = 0.0
for b in range(n):
dx, dy, dz = x[b] - x[a], y[b] - y[a], z[b] - z[a]
inv = 1.0 / (dx * dx + dy * dy + dz * dz + eps2) ** 0.5
s = m[b] * inv * inv * inv
sx += s * dx; sy += s * dy; sz += s * dz
ax[a], ay[a], az[a] = sx, sy, sz
return ax, ay, az
pts = (n - 2) ** 2
t = {
"Python puro": [mejor_s(lambda: suma_py(rl)) * 1e9 / len(rl),
mejor_s(lambda: jacobi_py(ul)) * 1e9 / (nl - 2) ** 2,
mejor_s(lambda: acel_py(xl, yl, zl, ml), 2) * 1e9 / npy ** 2],
"NumPy": [mejor_s(lambda: r.sum(), 5) * 1e9 / r.size,
mejor_s(lambda: jacobi_np(u), 5) * 1e9 / pts,
mejor_s(lambda: acel_np(x, y, z, m), 3) * 1e9 / nb ** 2],
}
for nombre in ("Debug (-O0)", "Release (-O3)", "Release + native", "native + fast-math"):
t[f"C++ {nombre}"] = [res_cpp[nombre][q][0] for q in ("suma", "jacobi", "nbody")]
ax, ay, az = acel_np(x, y, z, m)
ref_np = {"suma": r.sum(), "jacobi": jacobi_np(u).sum(), "nbody": (np.abs(ax) + np.abs(ay) + np.abs(az)).sum()}
print("Mismos resultados que C++: mayor diferencia relativa con NumPy entre las cinco configuraciones,")
print("fast-math incluida (C++ imprime 11 cifras, así que el mínimo visible es del orden de 1e-11):")
print(" " + ", ".join(f"{nom} {max(abs(res_cpp[c][q][3] - v) / abs(v) for c in res_cpp):.1e}"
for (q, v), nom in zip(ref_np.items(), ("suma", "Jacobi", "N cuerpos"))))
ref = t["C++ Release + native"]
print(f"\nns por unidad de trabajo y, entre paréntesis, cuántas veces más lento que C++ Release + native:")
print(f" {'':28s}{'suma':>18s}{'Jacobi':>18s}{'N cuerpos':>20s}")
for nombre, v in t.items():
print(f" {nombre:28s}" + "".join(f"{a:10.3f} ({a / b:6.1f})" for a, b in zip(v, ref)))
bw = max(res_cpp[c]["copia"][2] for c in res_cpp) # el mejor de las cinco medidas de la copia
print(f"\nTecho de memoria medido (copiar 128 MiB): {bw:.1f} GB/s con un hilo.")
for q, inten, nom in (("suma", 1 / 8, "suma, 1/8 flop/B"), ("jacobi", 4 / 16, "Jacobi, 1/4 flop/B")):
mejor = max(res_cpp[c][q][1] for c in res_cpp)
print(f" {nom}: techo {inten * bw:.2f} GFLOP/s; lo mejor medido {mejor:.2f} GFLOP/s ({mejor / (inten * bw):.0%})")
nb_best = max(res_cpp[c]["nbody"][1] for c in res_cpp)
print(f" N cuerpos: unas {nb:d} interacciones por cuerpo leídas de caché; lo mejor medido {nb_best:.1f} GFLOP/s")npm run lab and open the connection link.Exact figures change between runs (the reference machine is shared with other processes), but the pattern is stable. The lesson verification run produced:
- Pure Python versus C++ (
Release + native): 23 times slower for the sum, 116 for the stencil and 131 for bodies. Each Python iteration creates and destroysfloatobjects, looks up names in dictionaries and dispatches each operation at runtime; the next lesson measures that interpreter overhead. - NumPy versus C++: tied for the sum (1.0 times), because
r.sum()is already a compiled loop over contiguous data; 14 times slower for the stencil and another 14 for bodies. NumPy does not compute slowly: each operation is a full pass over memory with a temporary array. The stencil creates four views and three 32 MiB temporaries, and the -body version materializes difference matrices. NumPy runs in Windows Python and C++ in WSL, and the cost of allocating new memory for each temporary also counts. - Debug versus Release:
Debugwas 7 to 14 times slower thanRelease (-O3)depending on the kernel. Many projects default to a configuration you do not want for measurement. -O2,-O3and-march=nativeare close to each other (within a factor of 1.5) and far from-O0, with a different reason for the lack of another jump in each kernel. The sum indoublewithout-ffast-mathis a chain of dependent additions: it is limited by addition latency, not memory (in the compiler figure,sumatakes the same time in L1 as in RAM). The stencil is memory-bound. And for bodies the inner loop is a reduction overjwhich, like the sum, gcc does not reorder without permission: at the end of the CMake cell, the vectorization report (-fopt-info-vec) mentions that loop only when-ffast-mathis added. (Thesumaloop appears in both cases, but the compiler figure already showed that “vectorized” can mean an ordered reduction that gains nothing.)-ffast-mathspeeds up bodies by a little over 50% (13.1 GFLOP/s versus 8.4 withRelease + native), because it now vectorizes the inner reduction. The 128 MiB sum drops from 0.68 to 0.32 ns per element: with eight independent accumulators it no longer waits for each addition’s latency and becomes memory-bound. The cell also compares the five configurations’ checksums, including-ffast-math, with NumPy’s, and they agree in every figure C++ prints (relative differences at most ): here reassociation is harmless, because rounding in these kernels barely depends on order. It was not harmless for Kahan summation.- Roofline. With the 128 MiB copy at 39.1 GB/s as the memory ceiling, the best sum (
-ffast-math) reached 64% of the ceiling and the best stencil 61%. There is a quantitative explanation for the stencil: the count of 16 bytes per point ignores that before writingv, the cache reads its line (write-allocate), so actual traffic is 24 bytes per point and the effective ceiling is two thirds of the calculated one, about 6.5 GFLOP/s. The measured 5.96 GFLOP/s is 91% of that effective ceiling: the stencil moves about 36 GB/s, almost all bandwidth. The single-thread ceiling measurement also varies between runs on a shared machine, so it is worth repeating alongside each experiment, as the cell does. The sum without-ffast-math(1.5 GFLOP/s) reaches only 30% of the ceiling because of dependency-chain latency. bodies has high arithmetic intensity (the 2048 bodies fit in cache and each interaction is 20 flops counting square root and division as one each), so it is compute-bound; square root and division are much more expensive than addition, which is why it remains far from a core’s FMA peak.
What the compiler does with each flag
The lab’s last cell generates the compiler figure’s data: it compiles the five kernels with each flag set, extracts each function’s assembly and inner loop from .s (from a label to the conditional branch back to it), saves the -fopt-info-vec report and measures each variant in L1 and RAM, taking the best of three processes of 15 measurements. The kernel is compiled in a separate translation unit from the measurement program, so flags affect only it and the compiler cannot inline it into the measurement loop. The figure shows the explorer.json file written by a run on the reference machine. On repeating it, even there, times change (it is a shared machine) and assembly structure does not: in the lesson verification run, hot loops had exactly the same instructions as in the figure. On your machine, primarily compare ratios between flags.
KERNELS = r'''
#include <cstddef>
extern "C" {
float suma(const float* x, std::size_t n) {
float s = 0.0f;
for (std::size_t i = 0; i < n; ++i) s += x[i];
return s;
}
float kahan(const float* x, std::size_t n) {
float s = 0.0f, c = 0.0f;
for (std::size_t i = 0; i < n; ++i) {
float y = x[i] - c;
float t = s + y;
c = (t - s) - y; // lo que se perdió al redondear s + y
s = t;
}
return s;
}
void saxpy(float a, const float* x, float* y, std::size_t n) {
for (std::size_t i = 0; i < n; ++i) y[i] = a * x[i] + y[i];
}
void saxpy_restrict(float a, const float* __restrict x, float* __restrict y, std::size_t n) {
for (std::size_t i = 0; i < n; ++i) y[i] = a * x[i] + y[i];
}
void leaky_relu(const float* x, float* y, std::size_t n) {
for (std::size_t i = 0; i < n; ++i) {
if (x[i] > 0.0f) y[i] = x[i];
else y[i] = 0.01f * x[i];
}
}
}
'''
BENCH = r'''
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
extern "C" {
float suma(const float*, std::size_t);
float kahan(const float*, std::size_t);
void saxpy(float, const float*, float*, std::size_t);
void saxpy_restrict(float, const float*, float*, std::size_t);
void leaky_relu(const float*, float*, std::size_t);
}
template <class F> double ns_por_elemento(F f, std::size_t n) {
using reloj = std::chrono::steady_clock;
std::size_t veces = std::max<std::size_t>(1, (1u << 25) / n); // unos 32 M elementos por medida
double mejor = 1e300;
for (int t = 0; t < 15; ++t) { // mejor de 15 medidas
auto t0 = reloj::now();
for (std::size_t k = 0; k < veces; ++k) f();
double ns = std::chrono::duration<double, std::nano>(reloj::now() - t0).count();
mejor = std::min(mejor, ns / double(veces * n));
}
return mejor;
}
int main(int argc, char** argv) {
std::size_t n = std::strtoull(argv[1], nullptr, 10);
std::mt19937 gen(42);
std::uniform_real_distribution<float> U(0.0f, 1.0f);
std::vector<float> x(n), y(n), z(n);
for (auto& v : x) v = U(gen);
for (std::size_t i = 0; i < n; ++i) z[i] = 2.0f * x[i] - 1.0f;
double ref = 0.0, c = 0.0; // referencia: Kahan en double
for (float v : x) { double yy = v - c, t = ref + yy; c = (t - ref) - yy; ref = t; }
volatile float sumidero = 0;
float rs = suma(x.data(), n), rk = kahan(x.data(), n);
std::printf("suma %.4f %.6e %.17g\n", ns_por_elemento([&] { sumidero = suma(x.data(), n); }, n), (rs - ref) / ref, double(rs));
std::printf("kahan %.4f %.6e %.17g\n", ns_por_elemento([&] { sumidero = kahan(x.data(), n); }, n), (rk - ref) / ref, double(rk));
std::printf("saxpy %.4f 0 0\n", ns_por_elemento([&] { saxpy(1e-3f, x.data(), y.data(), n); }, n));
std::printf("saxpy_restrict %.4f 0 0\n", ns_por_elemento([&] { saxpy_restrict(1e-3f, x.data(), y.data(), n); }, n));
std::printf("leaky_relu %.4f 0 0\n", ns_por_elemento([&] { leaky_relu(z.data(), y.data(), n); }, n));
for (auto& v : z) v = std::fabs(v); // misma función, rama predecible
std::printf("relu_positivos %.4f 0 0\n", ns_por_elemento([&] { leaky_relu(z.data(), y.data(), n); }, n));
std::printf("ref %.17g\n", ref);
}
'''
FLAGS = ["-O0", "-O2", "-O3", "-O3 -march=native", "-O3 -march=native -ffast-math"]
FUNCS = ["suma", "kahan", "saxpy", "saxpy_restrict", "leaky_relu"]
escribe("flags/kernels.cpp", KERNELS)
escribe("flags/bench.cpp", BENCH)
d = LAB / "flags"
def funciones_asm(s):
"""Separa el .s por función y quita directivas: queda lo que verías en Compiler Explorer."""
out, actual = {}, None
for linea in s.splitlines():
m = re.match(r"^([A-Za-z_]\w*):", linea)
if m and m.group(1) in FUNCS:
actual = m.group(1); out[actual] = []; continue
if actual is None:
continue
t = linea.strip()
if t.startswith(".size") or t.startswith(".LFE"):
actual = None; continue
if re.match(r"^\.L\w+:", t) and not t.startswith(".LFB"):
out[actual].append(t)
elif t and not t.startswith(".") and not t.startswith("#"):
out[actual].append(" " + re.sub(r"\s+", " ", t))
return out
VECT = re.compile(r"ymm|\bv?(add|sub|mul|div|max|min|blendv|cmp\w*|f\w*madd\w*)p[sd]\b")
es_vectorial = lambda l: bool(VECT.search(l)) # operación empaquetada (varios carriles a la vez)
def bucle_caliente(lineas):
"""El bucle interno: de una etiqueta al salto condicional que vuelve a ella. Si hay varios, el más vectorial."""
pos = {l[:-1]: i for i, l in enumerate(lineas) if l.endswith(":")}
bucles = []
for j, l in enumerate(lineas):
m = re.match(r"\s+j(?!mp)\w+ (\.L\w+)$", l)
# salto hacia atrás sin un ret en medio: es un bucle, no un salto a la salida
if m and m.group(1) in pos and pos[m.group(1)] < j and not any(
lineas[k].strip() == "ret" for k in range(pos[m.group(1)], j)):
bucles.append((pos[m.group(1)], j))
if not bucles:
return None
vec = lambda b: sum(es_vectorial(lineas[k]) for k in range(b[0], b[1] + 1))
return max(bucles, key=lambda b: (vec(b), -(b[1] - b[0])))
# líneas del fuente que pertenecen a cada función, para repartir el informe de vectorización
_lin = KERNELS.splitlines()
_ini = {f: next(i + 1 for i, l in enumerate(_lin) if re.search(rf"\b{f}\(", l)) for f in FUNCS}
_ord = sorted(_ini.values()) + [len(_lin) + 1]
rango = {f: (a, _ord[_ord.index(a) + 1]) for f, a in _ini.items()}
datos = {"cpu": "", "compilador": "", "flags": FLAGS, "funcs": {}}
datos["compilador"] = sh("g++ --version | head -1").stdout.strip()
datos["cpu"] = sh("grep -m1 'model name' /proc/cpuinfo | cut -d: -f2").stdout.strip()
for k, fl in enumerate(FLAGS):
r = sh(f"g++ -std=c++20 {fl} -fno-asynchronous-unwind-tables -masm=intel -S kernels.cpp -o k{k}.s "
f"-fopt-info-vec-optimized-missed 2> vec{k}.txt && g++ -std=c++20 {fl} -c kernels.cpp -o k{k}.o && "
f"g++ -std=c++20 -O2 bench.cpp k{k}.o -o bench{k}", cwd=d)
assert r.returncode == 0, r.stderr
asm = funciones_asm((d / f"k{k}.s").read_text(encoding="utf-8"))
informe = (d / f"vec{k}.txt").read_text(encoding="utf-8")
for f in FUNCS:
lin = asm[f]
b = bucle_caliente(lin)
e = datos["funcs"].setdefault(f, {"asm": [], "loop": [], "vec": [], "t_l1": [], "t_ram": [], "err": []})
e["asm"].append(lin)
e["loop"].append(list(b) if b else None)
for f in FUNCS:
a, b = rango[f]
notas = []
for l in informe.splitlines():
m = re.match(r"kernels\.cpp:(\d+):\d+: (.*)", l)
if m and a <= int(m.group(1)) < b and m.group(2) not in notas:
notas.append(m.group(2))
datos["funcs"][f]["vec"].append(notas)
for n, clave in ((4096, "t_l1"), (1 << 24, "t_ram")):
# tres procesos y el mínimo de cada medida: la máquina puede estar ocupada con otras cosas
mejor = {}
for _ in range(3):
for linea in sh(f"./bench{k} {n}", cwd=d).stdout.splitlines():
p = linea.split()
if p[0] != "ref":
t, e = float(p[1]), float(p[2])
mejor[p[0]] = (min(t, mejor.get(p[0], (1e9, 0))[0]), e)
for f in FUNCS:
datos["funcs"][f][clave].append(mejor[f][0])
if clave == "t_ram" and f in ("suma", "kahan"):
datos["funcs"][f]["err"].append(mejor[f][1])
if clave == "t_ram":
datos.setdefault("relu_pos", []).append(mejor["relu_positivos"][0])
print(f"{datos['compilador']} en {datos['cpu']}")
print("Por kernel y flags: ns por elemento con n = 4096 (en L1) y n = 16 M (en RAM), error relativo")
print("de las sumas con n = 16 M e instrucciones del bucle caliente (las vectoriales entre paréntesis).")
for f in FUNCS:
e = datos["funcs"][f]
print(f"\n{f}")
for k, fl in enumerate(FLAGS):
lin, b = e["asm"][k], e["loop"][k]
cuerpo = lin[b[0] + 1:b[1] + 1] if b else []
nv = sum(es_vectorial(l) for l in cuerpo)
err = f" err {e['err'][k]:+.1e}" if e["err"] else ""
print(f" {fl:29s} {e['t_l1'][k]:6.3f} | {e['t_ram'][k]:6.3f} ns{err} bucle {len(cuerpo):2d} ({nv:2d})")
print("\nleaky_relu con n = 16 M y todos los x > 0 (la rama siempre va al mismo lado): " +
", ".join(f"{fl} {t:.3f} ns" for fl, t in zip(FLAGS, datos["relu_pos"])))
(LAB / "flags" / "explorer.json").write_text(json.dumps(datos), encoding="utf-8")npm run lab and open the connection link.The lesson’s other two effects of -ffast-math, a disappearing NaN check and subnormals becoming zero even when only linking with the option, can be seen with two three-line programs:
escribe("fm/nan.cpp", r'''#include <cmath>
bool es_nan(double x) { return std::isnan(x); }
''')
escribe("fm/subnormal.cpp", r'''#include <cstdio>
int main(int argc, char**) {
volatile double x = 1e-310 * argc; // un subnormal (lección 1), calculado en tiempo de ejecución
std::printf("1e-310 * 1 = %g\n", x * 1.0);
}
''')
d = LAB / "fm"
for fl in ("-O2", "-O2 -ffast-math"):
r = sh(f"g++ {fl} -masm=intel -fno-asynchronous-unwind-tables -S nan.cpp -o - | "
"sed -n '/^_Z6es_nand:/,/ret/p' | grep -v -E '^_Z|endbr64|^\\s*\\.'", cwd=d)
print(f"es_nan con {fl}: " + " ; ".join(l.strip() for l in r.stdout.splitlines()))
print()
casos = [("sin -ffast-math", "-O2", "-O2"),
("-ffast-math al compilar y enlazar", "-O2 -ffast-math", "-ffast-math"),
("-ffast-math solo al enlazar", "-O2", "-ffast-math")]
for nombre, fc, fe in casos:
r = sh(f"g++ {fc} -c subnormal.cpp -o s.o && g++ {fe} s.o -o s && ./s", cwd=d)
print(f"{nombre:34s} {r.stdout.strip()}")npm run lab and open the connection link.Templates and Eigen in the lab
The template cell instantiates suma_kahan for float and double, lists both instance symbols, shows the type of an Eigen expression and solves a linear system using LU with partial pivoting. If Eigen is not installed (sudo apt install libeigen3-dev), it downloads its headers, a few MiB.
import tarfile, urllib.request
# Eigen es solo cabeceras: si no está en el sistema, se descarga la versión 3.4.0 junto al laboratorio.
eig = LAB / "eigen-3.4.0"
if sh("test -f /usr/include/eigen3/Eigen/Dense").returncode == 0:
INC = "-I/usr/include/eigen3"
else:
if not (eig / "Eigen" / "Dense").exists():
url = "https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.gz"
tgz = LAB / "eigen-3.4.0.tar.gz"
urllib.request.urlretrieve(url, tgz)
with tarfile.open(tgz) as t:
t.extractall(LAB, members=[m for m in t.getmembers() if m.name.startswith("eigen-3.4.0/Eigen/")],
filter="data")
tgz.unlink()
INC = "-Ieigen-3.4.0"
escribe("plantillas.cpp", r'''#include <Eigen/Dense>
#include <chrono>
#include <concepts>
#include <cstdio>
#include <cxxabi.h>
#include <span>
#include <typeinfo>
#include <vector>
// Una sola definición genérica; el compilador genera una versión por cada T que se use.
template <std::floating_point T>
T suma_kahan(std::span<const T> x) {
T s = 0, c = 0;
for (T v : x) { T y = v - c; T t = s + y; c = (t - s) - y; s = t; }
return s;
}
// La forma ingenua de sumar vectores: cada + devuelve un vector nuevo.
std::vector<double> operator+(const std::vector<double>& a, const std::vector<double>& b) {
std::vector<double> r(a.size());
for (std::size_t i = 0; i < a.size(); ++i) r[i] = a[i] + b[i];
return r;
}
template <class F> double mejor_ms(F f) {
double m = 1e300;
for (int r = 0; r < 7; ++r) {
auto t0 = std::chrono::steady_clock::now(); f();
m = std::min(m, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
}
return m;
}
int main() {
std::vector<float> xf(10'000'000, 0.1f);
std::vector<double> xd(10'000'000, 0.1);
float ingenua = 0.0f;
for (float v : xf) ingenua += v;
std::printf("10^7 veces 0.1: suma_kahan<float> %.4f, suma_kahan<double> %.4f, bucle ingenuo en float %.4f\n",
double(suma_kahan<float>(xf)), suma_kahan<double>(xd), double(ingenua));
using Eigen::VectorXd;
const int n = 1 << 22;
VectorXd a = VectorXd::LinSpaced(n, 0.0, 1.0), b = a.array().sin().matrix(), c = a.array().cos().matrix(), d(n);
auto expr = a + b + c; // aún no se ha calculado nada
int st;
char* nombre = abi::__cxa_demangle(typeid(expr).name(), nullptr, nullptr, &st);
std::printf("tipo de a + b + c: %.150s...\n", nombre);
std::printf("sizeof(expr) = %zu bytes (referencias a los operandos, no %zu bytes de datos)\n", sizeof(expr), sizeof(double) * n);
std::free(nombre);
std::vector<double> va(a.data(), a.data() + n), vb(b.data(), b.data() + n), vc(c.data(), c.data() + n), vd;
double te = mejor_ms([&] { d = a + b + c; });
double tv = mejor_ms([&] { vd = va + vb + vc; });
std::printf("d = a + b + c con n = 2^22: Eigen %.2f ms (un bucle), vector con operator+ %.2f ms (dos bucles y un temporal)\n", te, tv);
Eigen::MatrixXd A = Eigen::MatrixXd::Random(500, 500) + 500.0 * Eigen::MatrixXd::Identity(500, 500);
VectorXd x0 = VectorXd::Ones(500), rhs = A * x0;
VectorXd x = A.partialPivLu().solve(rhs);
std::printf("A x = b con LU con pivoteo parcial (n = 500): error relativo %.1e, residuo relativo %.1e\n",
(x - x0).norm() / x0.norm(), (A * x - rhs).norm() / rhs.norm());
}
''')
r = sh(f"g++ -std=c++20 -O3 -march=native -DNDEBUG {INC} plantillas.cpp -o plantillas && ./plantillas")
print(r.stdout if r.returncode == 0 else r.stderr[-2000:])
# Sin optimizar, las instancias no se integran en main y se ven como símbolos (W: débiles, por si
# otra unidad de traducción instancia lo mismo; el enlazador se queda con una).
r = sh(f"g++ -std=c++20 -O0 {INC} -c plantillas.cpp -o p0.o && nm -C p0.o | grep suma_kahan")
print("Instancias de la plantilla en el objeto (-O0):\n" + r.stdout)npm run lab and open the connection link.With ten million summands equal to 0.1f, the naive loop in float gives 1087937 instead of one million: an error of 8.8%. When the sum is large, each s + 0.1f rounds to the nearest multiple of the spacing of float in that range, and rounding is no longer random: between and each step adds exactly , and above , . (You can check with np.cumsum in float32, which reproduces 1087937.) The same Kahan template instantiated in float gives exactly one million (the exact sum of the stored 0.1f, , rounded to float). The system is solved with relative error of order , as expected for a well-conditioned matrix.
Lab 2: sanitizers as a safety net
The cells use g++ with -fsanitize=address,undefined. If you work with MSVC on Windows, /fsanitize=address (with /Zi for line numbers in the report) provides the same AddressSanitizer; UBSan is unavailable there, so you will need g++ or clang in WSL to find signed overflow.
The first cell generates the gallery data: it compiles each case with -O0, -O2 and -O1 -g -fsanitize=address,undefined, runs it with a 2-second limit and extracts the important report lines.
CASOS = {
"desbordamiento": r'''#include <cstdio>
int main() {
int n = 0;
for (int i = 1; i > 0; i *= 2) // ¿cuántas veces se duplica i antes de pasar a negativo?
++n;
std::printf("n = %d\n", n);
}
''',
"fuera_de_rango": r'''#include <cstdio>
int tabla[4] = {2, 3, 5, 7};
__attribute__((noinline)) bool esta_en_tabla(int v) {
for (int i = 0; i <= 4; ++i) // <= en lugar de <: lee tabla[4]
if (tabla[i] == v) return true;
return false;
}
int main() { std::printf("esta_en_tabla(42) = %d\n", esta_en_tabla(42)); }
''',
"uso_tras_liberar": r'''#include <cstdio>
#include <vector>
int main() {
std::vector<double> v = {1.0, 2.0, 3.0};
double& primero = v[0];
v.push_back(4.0); // capacidad agotada: v se muda a otro bloque
primero = 10.0;
std::printf("primero = %g, v[0] = %g\n", primero, v[0]);
}
''',
"aliasing": r'''#include <cstdio>
__attribute__((noinline)) int f(int* i, float* x) {
*i = 1;
*x = 0.0f; // si x apunta a *i, sobrescribe sus bits
return *i;
}
int main() {
int a = 0;
std::printf("f = %d\n", f(&a, reinterpret_cast<float*>(&a)));
}
''',
}
VARIANTES = [("-O0", "-O0"), ("-O2", "-O2"),
("ASan + UBSan", "-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer")]
def resumen_informe(texto):
"""Las líneas que importan de un informe de ASan o UBSan."""
claves = []
for l in texto.splitlines():
l = l.strip()
if ("runtime error" in l or "ERROR: AddressSanitizer" in l or re.match(r"(READ|WRITE) of size", l)
or re.match(r"#0 0x\w+ in ", l) or "is located" in l or "by thread" in l
or "SUMMARY:" in l) and "ubsan_data" not in l:
l = l.replace(_ruta_wsl(LAB) + "/", "").replace(str(LAB) + "/", "") # sin rutas largas
l = re.sub(r"(\.\./)+src/libsanitizer/\w+/", "", l)
l = re.sub(r"\b\w+/(\w+\.cpp:)", r"\1", l)
l = re.sub(r"0x[0-9a-f]{6,}", "0x…", l)
l = re.sub(r"^==\d+==", "", l)
if l not in claves:
claves.append(l)
return claves[:10]
galeria = {}
for nombre, codigo in CASOS.items():
escribe(f"ub/{nombre}.cpp", codigo)
galeria[nombre] = {"codigo": codigo, "salidas": []}
for etiqueta, fl in VARIANTES:
r = sh(f"g++ -std=c++20 {fl} -Wall -Wextra {nombre}.cpp -o {nombre}.bin 2> {nombre}.warn; "
f"cat {nombre}.warn | grep -E 'warning' | head -3; "
f"echo '@@'; timeout 2 ./{nombre}.bin; echo \"@@$?\"", cwd=LAB / "ub")
avisos, resto = r.stdout.split("@@", 1)
salida, codigo_salida = resto.rsplit("@@", 1)
codigo_salida = int(codigo_salida.strip() or 0)
galeria[nombre]["salidas"].append({
"flags": etiqueta, "stdout": salida.strip(), "exit": codigo_salida,
"colgado": codigo_salida == 124, "avisos": [re.sub(r"^\S+:\d+:\d+: ", "", a) for a in avisos.strip().splitlines()],
"informe": resumen_informe(r.stderr)})
print(f"\n== {nombre}")
for s in galeria[nombre]["salidas"]:
estado = "no termina (cortado a los 2 s)" if s["colgado"] else (s["stdout"] or "(sin salida)")
print(f" {s['flags']:13s} -> {estado} [código {s['exit']}]")
for a in s["avisos"]:
print(f" aviso: {a[:110]}")
for l in s["informe"][:4]:
print(f" {l[:110]}")
(LAB / "ub" / "galeria.json").write_text(json.dumps(galeria, ensure_ascii=False), encoding="utf-8")npm run lab and open the connection link.The second cell is real work with sanitizers: a small numerical program (estimate by Monte Carlo with a congruential generator and histogram the samples) with three seeded errors. The cycle is the one you will follow with your own code: compile with sanitizers, run, read the report, fix and repeat until the program finishes cleanly. The cell applies the three fixes in the order the reports request them.
MONTECARLO = r'''// montecarlo.cpp: estima pi por Monte Carlo con un generador congruencial y dibuja
// un histograma de las muestras. Tiene tres errores sembrados.
#include <cstdint>
#include <cstdio>
#include <vector>
int estado = 12345;
double uniforme() { // congruencial lineal (lección 17)
estado = estado * 1103515245 + 12345; // ERROR A
return ((estado >> 8) & 0xFFFFFF) / 16777216.0; // 24 bits altos, en [0, 1)
}
double estima_pi(int n, std::vector<int>& hist) {
int dentro = 0;
for (int k = 0; k < n; ++k) {
double x = uniforme(), y = uniforme();
dentro += (x * x + y * y < 1.0);
hist[int(x * hist.size())]++;
}
return 4.0 * dentro / n;
}
int main() {
std::vector<int> hist(10, 0);
std::vector<double> lotes = {estima_pi(20000, hist)};
const double& anterior = lotes.back(); // ERROR B
for (int k = 1; k < 4; ++k) {
lotes.push_back(estima_pi(20000, hist));
std::printf("lote %d: pi ~ %.4f (cambio %+.4f)\n", k, lotes.back(), lotes.back() - anterior);
}
for (int b = 0; b <= 10; ++b) // ERROR C
std::printf("%d ", hist[b]);
std::printf("\n");
}
'''
# Las tres correcciones, en el orden en que los informes las piden.
ARREGLOS = [
("int estado = 12345;",
"std::uint32_t estado = 12345; // sin signo: aritmética módulo 2^32"),
("const double& anterior = lotes.back(); // ERROR B",
"double anterior = lotes.back(); // una copia, no una referencia"),
("b <= 10; ++b) // ERROR C",
"b < 10; ++b) // los índices válidos son 0..9"),
]
SAN = "-std=c++20 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer"
fuente = MONTECARLO
for paso in range(len(ARREGLOS) + 1):
escribe("san/montecarlo.cpp", fuente)
r = sh(f"g++ {SAN} montecarlo.cpp -o mc && ./mc", cwd=LAB / "san")
informe = resumen_informe(r.stderr)
print(f"--- ejecución {paso + 1}: código de salida {r.returncode}")
print(" salida: " + " | ".join(r.stdout.strip().splitlines()[-2:]))
for l in informe[:4]:
print(" " + l[:120])
if paso < len(ARREGLOS):
viejo, nuevo = ARREGLOS[paso]
assert viejo in fuente
fuente = fuente.replace(viejo, nuevo)
print(f" corrección: {nuevo.split('//')[0].strip()}")npm run lab and open the connection link.Read it as a debugging diary:
- First run. UBSan reports at line 9 that
12345 * 1103515245does not fit in anint: the classic congruential generator multiplies in signed arithmetic and overflows on the first call. UBSan reports and continues (its default behavior), then ASan stops the program with anheap-use-after-free: an 8-byte read at line 29, which printslotes.back() - anterior. The overflow fix is to usestd::uint32_t, whose arithmetic is modulo by definition. - Second run. Use after free remains, now with more detail: the read falls “0 bytes inside an 8-byte region”, the block of an
doublethat hadloteswhen referenceanteriorwas taken. The firstpush_backreallocated it. The fix is to save a copy of the value. - Third run. ASan finds an
heap-buffer-overflow: a 4-byte read “0 bytes after a 40-byte region” at line 32. Forty bytes are the histogram’s 10intvalues; the loopb <= 10reads the eleventh. - Fourth run. No reports: the program prints its estimates and histogram.
A practical detail: in runs that abort, normal program output does not appear even if something was printed before the error. When standard output goes to a pipe, the C library buffers it and ASan terminates the process without flushing it. If you need that output to debug, print to stderr or flush the buffer.
Common mistakes
Connections
In the next lesson you will call these kernels from Python without copying data and compare C++, Numba and NumPy fairly. Large-model training and inference kernels and PyTorch extensions are written in C++ and CUDA C++ and registered as custom operators (custom operator registration); the compilation model, templates and memory discipline from this lesson are the same. Low-latency backtesting and execution engines in the backtesting project are also often implemented in C++ (backtester architecture). Undefined behavior in native code is a classic source of vulnerabilities, which will reappear when studying reliability and security of ML systems.
Further reading: Stroustrup’s A Tour of C++ is the shortest tour of the modern language; Meyers’ Effective Modern C++ is a reference on moves, auto and smart pointers; cppreference.com is the standard reference; Agner Fog’s Optimizing software in C++ covers the machine cost of each construct; and the AddressSanitizer paper explains its internals.
Exercises
const std::vector<double>& crea(std::size_t n) { std::vector<double> v(n, 1.0); return v; }int x, gcc compiles if (x + 1 < x) desbordamiento(); at -O2 as if the if did not exist. Why can it do that?std::vector<std::vector<double>> a poor representation for a dense matrix in high-performance code? Select all correct reasons.More than one answer may be correct.
std::vector<double> b = std::move(a);, which statement is correct?if (std::isnan(perdida)) abortar(); at every step. The team compiles everything with -O3 -ffast-math and one day the loss becomes NaN. What happens?template <class T> T suma_kahan(std::span<const T>); in kahan.hpp, define it in kahan.cpp and call it as suma_kahan<double>(x) from main.cpp. Everything compiles, but the linker fails with “undefined reference to double suma_kahan<double>”. Why?std::vector objects, how many bytes in total does each row of a std::vector<std::vector<double>> with 4 columns occupy, counting the row's vector object and its block?for (int i = 1; i > 0; i *= 2) ++n;, if no evaluation of i * 2 overflows, the condition i > 0 is true at every check and the loop never ends. Therefore a compiler assuming no overflow may remove the check.Step 1 of 3. What property do you prove by induction?
KAHAN_CPP so that kahan computes the compensated Kahan sum of a std::span<const float>. The tests compile your function in a separate translation unit with -O3 -march=native and -O3 -march=native -ffast-math, sum uniform values in and compare with a double-precision reference: with -O3 relative error must be below , and the second test checks that -ffast-math breaks it. It needs the sh and escribe utilities from lab 1's first cell.KAHAN_CPP = r'''
#include <span>
float kahan(std::span<const float> x) {
float s = 0.0f;
// tu código: añade la compensación c que recupera lo que se pierde al redondear s + y
for (float v : x) s += v;
return s;
}
'''Summary
- C++ compiles each translation unit separately and the linker joins symbols: hence headers, the one-definition rule, name mangling,
extern "C"and ABI incompatibility between MSVC and MinGW. CMake describes the project by targets; build type (Debug,Release) determines whether it is optimized. - Objects are values; references and pointers own nothing. Moving costs and copying . RAII ties each resource to an owner’s lifetime and the rule of zero means you almost never write
delete. Reallocations ofstd::vectorinvalidate references and pointers to elements. - A dense matrix is a contiguous block indexed by . Templates generate an optimized version per type; Eigen uses them to fuse expressions into one loop without temporaries.
- Undefined behavior is a contract exploited by the optimizer: infinite loops, rewritten functions, reads not repeated. ASan and UBSan detect it at runtime at moderate cost; strict aliasing is prevented, not detected.
-O2and-O3change cost by orders of magnitude;-march=nativeunlocks AVX2 and FMA. The vectorization report tells what the compiler attempted; the assembly, what it did.-ffast-mathreassociates, removes Kahan compensation, turnsisnanintofalseand zeros subnormals throughout the process.
-ffast-math where order matters), it gives you vector code at hardware speed; if you break them, it reasons from false premises without warning. Read the assembly and use sanitizers to know which case you are in.