2. Samples in Memory¶
Every chapter of PySDR manipulates arrays of IQ samples, and almost always they are NumPy arrays of type np.complex64. In this chapter we look at what those samples become in C++: how they are laid out in memory, how to move them between Python and C++ without any conversion at all, and how one of the most innocent-looking operators in the standard library, the complex multiplication a * b, can quietly cost you a factor of three. Along the way we meet the compiler flags that control floating-point behavior, which will come back in every later chapter.
std::complex<float> Is Just Two Floats¶
PySDR’s IQ Files and SigMF chapter explains that an IQ recording is usually nothing more than interleaved numbers, I0 Q0 I1 Q1 I2 Q2 and so on, with no header at all. np.complex64 is exactly that: two 32-bit floats per sample, real part first. In C++ the matching type is std::complex<float>, and the language standard guarantees that it has the same layout. The relevant paragraph of the C++ standard ([complex.numbers.general]) says that for an array a of complex<T>, reinterpret_cast<T*>(a)[2*i] is the real part of a[i] and reinterpret_cast<T*>(a)[2*i+1] is the imaginary part. This guarantee exists precisely so that C++ code can share buffers with C, Fortran and, as it turns out, NumPy.
So reading a file that PySDR wrote with samples.astype(np.complex64).tofile('recording.iq') is a single fread:
using cf32 = std::complex<float>;
static_assert(sizeof(cf32) == 2 * sizeof(float), "layout must match numpy complex64");
std::vector<cf32> read_cf32(std::string const& path)
{
std::FILE* f = std::fopen(path.c_str(), "rb");
if (!f) throw std::runtime_error("cannot open " + path);
std::fseek(f, 0, SEEK_END);
long bytes = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
std::vector<cf32> x(static_cast<std::size_t>(bytes) / sizeof(cf32));
x.resize(std::fread(x.data(), sizeof(cf32), x.size(), f));
std::fclose(f);
return x;
}
and np.fromfile('recording.iq', np.complex64) reads what C++ writes with fwrite. The complete program is code/examples/iq_file.cpp. Notice what is not there: no parsing, no conversion loop, no copy into a different structure. This “same bytes on both sides” property is why it is so easy to prototype in Python and move the hot path to C++ later, and it is also how GNU Radio’s gr_complex (a typedef for std::complex<float>) is passed to and from NumPy in its Python bindings.
The static_assert costs nothing at run time; it turns an assumption into a compile error if it is ever violated. It is a good habit wherever your code depends on a layout.
Integer Samples¶
Most SDR front ends deliver 12- to 16-bit integers, not floats, and PySDR mentions “Sean’s 4x rule”: stored as interleaved int16, an IQ recording takes four bytes per sample. C++ has no std::complex<int16_t> you would want to compute with (the standard only specifies complex for floating-point types), so integer IQ is usually handled as a plain struct of two std::int16_t or as a flat array, and converted to float as early as possible:
// sc16 (interleaved int16) -> cf32, scaled to [-1, 1)
void sc16_to_cf32(std::span<const std::int16_t> in, std::span<cf32> out)
{
constexpr float scale = 1.0f / 32768.0f;
for (std::size_t i = 0; i < out.size(); ++i)
out[i] = cf32(in[2 * i] * scale, in[2 * i + 1] * scale);
}
The loop is simple enough that the compiler vectorizes it on its own, and VOLK offers the same operation as volk_16i_s32f_convert_32f. Note the std::span: a pointer plus a length in one object, the C++20 way to say “a block of samples that somebody else owns”. It is what NumPy’s array view is to Python, and we use it for every process() function in this book.
The Most Expensive Asterisk in C++¶
Mixing a signal with a local oscillator, applying a phase correction, multiplying spectra in an FFT filter: complex multiplication is everywhere in SDR. So let’s measure the most basic version of it, multiplying two blocks of 4096 samples element by element:
void mul_std(cf32* out, const cf32* a, const cf32* b, std::size_t n)
{
for (std::size_t i = 0; i < n; ++i) out[i] = a[i] * b[i];
}
and, as a comparison, the same thing with the textbook formula \((a+jb)(c+jd) = (ac-bd) + j(ad+bc)\) written out by hand:
void mul_manual(cf32* out, const cf32* a, const cf32* b, std::size_t n)
{
for (std::size_t i = 0; i < n; ++i) {
const float ar = a[i].real(), ai = a[i].imag();
const float br = b[i].real(), bi = b[i].imag();
out[i] = cf32(ar * br - ai * bi, ar * bi + ai * br);
}
}
These two functions compute the same products. Here is how long they take per sample (benchmark code/bench/complex_mul.cpp, built with each compiler and flag combination by code/run_complex_mul.sh):
Compiler and flags |
|
hand-written formula |
|---|---|---|
Clang 21, |
0.99 |
0.33 |
Clang 21, |
0.33 |
0.33 |
Clang 21, |
0.16 |
0.16 |
GCC 16, |
0.66 |
0.21 |
GCC 16, |
0.21 |
0.21 |
GCC 16, |
0.21 |
0.21 |
Apple M1 performance core, Apple Clang 21.0 / libc++, Homebrew GCC 16.2 / libstdc++, -mcpu=apple-m1.
With both compilers and both standard libraries, the innocent * is about three times slower than four multiplications and two additions written by hand. Why?
What the Standard Asks For¶
The answer is infinity, literally. Consider \((\infty + j0) \cdot (1 + j1)\). Mathematically the result is \(\infty + j\infty\). But the textbook formula computes the real part as \(\infty \cdot 1 - 0 \cdot 1 = \infty\) (fine) and the imaginary part as \(\infty \cdot 1 + 0 \cdot 1 = \infty\) (fine), whereas \((\infty + j\infty)\cdot(0 + j1)\) gives \(\infty\cdot 0 - \infty \cdot 1\), which is \(\text{NaN} - \infty = \text{NaN}\), in both parts. An infinite number has turned into “not a number”. Annex G of the C standard (C11 draft N1570, G.5.1) therefore specifies that when the naive result is NaN in both parts, the implementation must check whether an operand was infinite and, if so, recover a properly infinite result. C++ standard libraries follow the same rules for std::complex.
Compilers implement this in a clever way: they compute the fast formula, then check whether both parts came out NaN, and only in that case call a slow library routine (__mulsc3, “multiply single-precision complex”). Here is the inner loop Clang generates for mul_std (annotations ours):
ldp s4, s5, [x10, #-4] ; load a[i] (one complex sample)
ldp s2, s3, [x9, #-4] ; load b[i]
fmul s0, s4, s2 ; ac
fmul s1, s5, s3 ; bd
fmul s6, s4, s3 ; ad
fmul s7, s5, s2 ; bc
fsub s0, s0, s1 ; re = ac - bd
fadd s1, s7, s6 ; im = ad + bc
fcmp s0, s0 ; is re NaN?
fccmp s1, s1, #0, vs ; ...and im NaN?
b.vs slow_path ; then go call __mulsc3
stp s0, s1, [x8, #-4] ; store out[i]
The slow path is never taken for ordinary samples, so the call itself costs nothing. The damage is done by the possibility of the call: a loop that might call a function in the middle cannot be vectorized, so the compiler processes one sample at a time with scalar instructions (s0, s1 are single 32-bit registers). The hand-written version has no such branch, and the compiler turns it into NEON instructions that process four samples at once (ld2.4s loads four complex numbers and de-interleaves them into a register of real parts and a register of imaginary parts).
You will find exactly this lesson written down in GNU Radio. Its Costas loop uses a helper from gnuradio-runtime/include/gnuradio/math.h (v3.10.12.0):
static inline void
fast_cc_multiply(gr_complex& out, const gr_complex cc1, const gr_complex cc2)
{
// The built-in complex.h multiply has significant NaN/INF checking that
// considerably slows down performance. While on some compilers the
// -fcx-limit-range flag can be used, this fast function makes the math consistent
// in terms of performance for the Costas loop.
float o_r, o_i;
o_r = (cc1.real() * cc2.real()) - (cc1.imag() * cc2.imag());
o_i = (cc1.real() * cc2.imag()) + (cc1.imag() * cc2.real());
out.real(o_r);
out.imag(o_i);
}
Three Ways Out, and What They Cost¶
1. Write the product by hand, in one small inline function, and use it in hot loops. This is what GNU Radio does and what we do in this book (cppsdr::cmul in code/include/cppsdr/nco.hpp). It is explicit, portable, and affects nothing else. The price: if a sample ever is infinite, you get NaN instead of infinity. In a receiver an infinite sample means something already went badly wrong upstream, so this is almost always acceptable.
2. Tell the compiler with -fcx-limited-range. Both Clang and GCC accept this flag, which says “use the naive formulas for complex multiplication and division, without the NaN checks”. As the table shows, it makes a * b exactly as fast as the hand-written version. It applies to a whole translation unit, which is both its strength (no code changes) and its weakness (it also changes complex division, where the naive formula can overflow for large values; you lose the scaling that protects it).
3. Use -ffast-math. This is the big hammer: it allows the compiler to assume there are no NaNs or infinities at all, to reorder additions as if floating-point math were associative, to flush tiny values to zero, and more. With Clang on the M1 it doubles the speed once more, because Clang then emits fcmla, the complex multiply-accumulate instruction that ARMv8.3 added specifically for this kind of code, which it does not use otherwise. (GCC 16 did not, so its numbers do not move.) The catch is that -ffast-math changes the meaning of every floating-point expression in the file, including ones where the order of operations matters for accuracy, and it breaks std::isnan. We will see in the FIR Filters in C++ chapter that it can even make some loops slower. Use it deliberately, per file, and measure; never as a global default.
Note
A quick way to see the generated assembly for yourself is Compiler Explorer: paste mul_std, pick Clang or GCC for ARM64 or x86-64, add -O3, and look for __mulsc3. Then add -fcx-limited-range and watch the vector instructions appear.
Two Smaller Traps¶
Magnitudes¶
PySDR uses np.abs(x) everywhere: envelope detection, PSD plots, normalising a signal. The C++ equivalent std::abs(z) for a complex number is implemented like std::hypot(re, im) (libc++ literally calls std::hypot; libstdc++ calls the C library’s cabsf), which avoids overflow and underflow in the intermediate square (it would be a shame if \(|10^{30}|\) overflowed just because \(10^{60}\) does not fit in a float). For samples in the range \(\pm 1\) that care is unnecessary, and std::sqrt(std::norm(z)) (std::norm is the squared magnitude, a historically unfortunate name) does the same job:
Operation |
default |
|
|---|---|---|
|
1.56 |
2.44 |
|
0.90 |
0.22 |
|
0.21 |
0.22 |
VOLK |
0.20 |
0.25 |
|
0.15 |
0.16 |
|
0.07 |
0.07 |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native. The last two rows process real floats (8192 per call).
The table holds a second surprise. std::sqrt(std::norm(z)) is faster than std::abs, but still more than four times slower than the same expression written out as std::sqrt(re*re + im*im). The reason is the one we just met: libc++’s std::norm checks whether either part is infinite before squaring (so that the result is infinity rather than NaN), and those checks keep the loop from being vectorized. With -ffast-math, which lets the compiler assume there are no infinities, the checks disappear and the gap closes. The hand-written version runs exactly as fast as VOLK’s dedicated kernel.
When you only need to compare magnitudes, for example to find the strongest FFT bin or to compare against a threshold, skip the square root altogether and compare std::norm(z) against the squared threshold.
Double Literals in Float Code¶
In C++, 0.5 is a double and 0.5f is a float. An expression like x * 0.5 + 0.25 with a float x is therefore computed in double precision and rounded back to float, which costs a conversion each way and halves the number of values per SIMD register. Kormanyos makes this point for microcontrollers in Real-Time C++ (4th ed., chapter 12), where the cost is software emulation; on a desktop CPU it is “only” a factor of about two, as the last two rows of the table show. NumPy has the mirror-image trap that PySDR warns about: many NumPy functions silently promote complex64 to complex128. In both languages, decide on your sample type once and keep it.
Key Takeaways¶
std::complex<float>has exactly the layout ofnp.complex64, guaranteed by the standard. Files and buffers move between Python and C++ without conversion.std::complexmultiplication follows the C standard’s rules for infinities. The check is cheap, but it blocks vectorization, makinga * babout 3x slower than the formula. Write the product by hand in hot loops, or use-fcx-limited-rangefor the file.-ffast-mathcan unlock special instructions (herefcmla), but it changes the semantics of all floating-point code in the file. Treat it as a measured, local decision.Use
std::norminstead ofstd::abswhen you do not need the actual magnitude, and keep float literals float.