11. Feedback Loops: the Costas Loop¶
In PySDR’s Synchronization chapter, the fine frequency correction is done by a Costas loop, a phase-locked loop for BPSK and QPSK. Its Python implementation is short and, unlike almost every other piece of DSP in PySDR, it is an explicit for loop over the samples:
for i in range(N):
out[i] = samples[i] * np.exp(-1j*phase) # adjust the input sample by the inverse of the estimated phase offset
error = np.real(out[i]) * np.imag(out[i]) # This is the error formula for 2nd order Costas Loop (e.g. for BPSK)
# Advance the loop (recalc phase and freq offset)
freq += (beta * error)
freq_log.append(freq * fs / (2*np.pi)) # convert from angular velocity to Hz for logging
phase += freq + (alpha * error)
# Optional: Adjust phase so its always between 0 and 2pi, recall that phase wraps around every 2pi
while phase >= 2*np.pi:
phase -= 2*np.pi
while phase < 0:
phase += 2*np.pi
There is a good reason it is a loop. To correct sample \(i\) we need phase, which was updated using the error of sample \(i-1\), which depended on phase from sample \(i-2\), and so on. The output feeds back into the input of the next step. NumPy cannot help here, because there is no array operation that expresses “each element depends on the result for the previous element through a nonlinear function”. This kind of code is where Python is weakest and C++ is strongest, and it shows up everywhere in a receiver: PLLs, Costas loops, symbol timing recovery (PySDR’s Mueller and Muller loop), AGCs, IIR filters, adaptive equalizers.
In this chapter we port the loop to C++, check that the port is exact, measure how much faster it is, and then use it to learn three things about tight feedback loops on modern CPUs: why they hit a speed limit that has nothing to do with the number of operations, why a “branchless” trick can make them slower, and how to get around the limit when you have more than one channel.
A Faithful Port¶
The test input is the situation PySDR’s loop sees after time synchronization: BPSK symbols at one sample per symbol (125 kHz), a residual frequency offset of \(-300\) Hz like in PySDR’s example, a phase offset and noise at 15 dB SNR. figure-generating-scripts/costas_reference.py generates 200 000 such samples, writes them to a file, and runs PySDR’s code on them.
The C++ port (code/include/cppsdr/costas.hpp) is a line-by-line translation. It is a template on the sample type, so the same source runs in float (what you would deploy) and in double (what NumPy computes in):
template <class T>
struct direct_port {
T alpha = T(0.132), beta = T(0.00932);
T phase = 0, freq = 0;
void process(std::span<const std::complex<T>> in, std::span<std::complex<T>> out,
T* freq_log = nullptr)
{
constexpr T two_pi = 2 * std::numbers::pi_v<T>;
for (std::size_t i = 0; i < in.size(); ++i) {
out[i] = in[i] * std::exp(std::complex<T>(0, -phase));
const T error = out[i].real() * out[i].imag();
freq += beta * error;
if (freq_log) freq_log[i] = freq;
phase += freq + alpha * error;
while (phase >= two_pi) phase -= two_pi;
while (phase < 0) phase += two_pi;
}
}
};
Because phase and freq are members, the loop keeps its state between calls to process(), so it works on a stream of blocks without any extra code: the same “carry the state” idea as the filters.
The double version reproduces PySDR’s output, run on the same file, to a maximum difference of \(2.4 \cdot 10^{-15}\), which is double-precision round-off. The float version tracks it to within float precision, and the plot of the frequency estimate shows both locking onto the offset in the same way:
Figure 11.1 Frequency estimate over the first 300 symbols: PySDR’s NumPy code (wide gray) and the C++ float port (blue) on the same input. As in PySDR, the loop locks after roughly 50 to 70 samples and then jitters around the true offset because of the noise.¶
How Much Faster?¶
Implementation |
ns/sample |
MS/s |
speed-up vs. PySDR |
|---|---|---|---|
Python: PySDR’s code, verbatim |
1916.7 |
0.52 |
1x |
Python: hand-tuned (cmath, plain complex) |
236.7 |
4.23 |
8x |
C++: direct port, |
32.1 |
31.16 |
60x |
C++: direct port, |
22.3 |
44.90 |
86x |
C++: GNU Radio style (sincos, branchless clip) |
24.8 |
40.31 |
77x |
C++: integer phase + lookup table |
20.6 |
48.48 |
93x |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native. Python 3.15, NumPy 2.5.
The verbatim PySDR loop needs almost 2 µs per sample. Most of that is not the math: every samples[i], np.exp(...) and np.real(...) on a single element creates and destroys a NumPy scalar object and goes through NumPy’s general dispatch machinery, which is built to be fast for arrays and is slow for one number at a time. Rewriting the loop for CPython (plain Python complex numbers, cmath.rect instead of np.exp, local variables, no logging) brings it down to 237 ns, eight times faster and still pure Python. If you have to stay in Python, that rewrite is worth knowing about; tools such as Numba exist precisely to compile loops like this one.
The C++ port runs at 22 ns per sample in float: 86 times faster than the original and about ten times faster than the best pure Python. At that speed one core could run the loop on a stream of 45 million symbols per second.
But why “only” 86 times, when the FIR filters in the previous chapter ran at a fraction of a nanosecond per tap?
The Latency Wall, Again¶
Twenty-two nanoseconds are about 70 clock cycles, for a loop body of roughly 15 arithmetic operations plus one sincos. The core could execute the operations themselves several times faster. What it cannot do is start them earlier. Follow the data through one iteration: the new phase goes into sincos (a function with a long internal chain of dependent operations), its result goes into the complex multiplication, the product goes into the error, the error into freq, freq and the error into phase, and the wrapped phase goes into the next sincos. Every step needs the result of the previous one, so the time per sample is the sum of the latencies along this chain, not the number of operations divided by the core’s throughput.
This is the same wall we met with the single accumulator in the FIR Filters in C++ chapter, but this time we cannot reorder our way around it: the feedback is the algorithm. It also explains the other rows of the table. The double version is slower because double-precision sincos takes longer. The integer phase accumulator with a lookup table (from Oscillators and Frequency Shifting) is a little faster, because a table lookup and an interpolation have a shorter latency than sincos, but the loop filter’s float arithmetic and the conversion of the phase step to an integer are still on the chain.
That observation leads straight to two experiments.
Branchless Is Not Free¶
GNU Radio’s Costas loop (gr-digital/lib/costas_loop_cc_impl.cc) clips the error to \([-1, 1]\) before using it, with a function from gnuradio/math.h:
static inline float branchless_clip(float x, float clip)
{
return 0.5 * (std::abs(x + clip) - std::abs(x - clip));
}
Avoiding branches is classic optimization advice, because a mispredicted branch costs the CPU 10 to 20 cycles of wasted work. But look at where this function sits: right on the critical chain, between the error and the update of freq. It adds an addition, a subtraction, two absolute values, another subtraction and a multiplication to the chain, and in a latency-bound loop every one of them costs its full latency. A plain if behaves very differently. The branch predictor guesses “not clipped” (which, at any reasonable SNR, is always right; in our test signal the error never exceeded 1), the core continues speculatively with the unclipped value, and the check runs off to the side of the critical chain. A well-predicted branch is not just cheap; it actually shortens the dependency chain compared to computing both sides. The measurement:
Clipping |
median |
range |
|---|---|---|
none |
20.9 |
20.8 - 22.6 |
if/else |
21.1 |
20.7 - 21.6 |
std::clamp |
22.9 |
22.8 - 23.1 |
branchless (GNU Radio) |
25.0 |
24.7 - 25.6 |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native.
The branchless version costs 20% more than no clipping at all, while the if costs nothing measurable. std::clamp sits in between: Clang compiles it to two compare-and-select pairs (fcmp and fcsel), which are data dependencies on the chain but shorter ones, while the if version stays a real, predicted branch. Pikus makes the general point in The Art of Writing Efficient Programs (chapter 3 and chapter 9): branchless code is the right tool against unpredictable branches, and only with a profile that shows mispredictions. For a branch that almost never fires, let the predictor do its job.
Choosing the Phase Detector at Run Time¶
GNU Radio’s loop supports BPSK, QPSK and 8PSK, so it has to pick a phase detector at run time. Its source carries an interesting comment:
// EXPENSIVE LINE with function pointer, switch was about 20% faster in testing.
// Left in for logic justification/reference. d_error = phase_detector_2(optr[i]);
switch (d_order) {
case 2: ...
C++ offers many ways to make this choice, and they make a nice compact tour of the language: a template parameter (decided at compile time, so the call is inlined), a switch, a function pointer, a virtual function, and std::function. We made the detector a policy, a template parameter of the loop, and wrote one small policy class for each mechanism (namespace costas::detect in costas.hpp). Because these differences are small, all variants run in the same program, interleaved, for seven rounds (see Appendix: Measuring Before Optimizing for why that matters):
Detector chosen by |
median |
range |
|---|---|---|
template |
25.0 |
24.6 - 25.3 |
switch |
24.7 |
24.6 - 25.4 |
function pointer |
24.9 |
24.6 - 28.3 |
virtual call |
24.7 |
24.6 - 28.4 |
std::function |
28.6 |
28.3 - 37.5 |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native.
On this machine and compiler, the template, the switch, the function pointer and the virtual call are indistinguishable: the spread between them is smaller than the spread between rounds. We could not reproduce the 20% from GNU Radio’s comment, which was presumably measured on different hardware with a different compiler; branch predictors for indirect calls have become very good, and an indirect call whose target never changes is predicted as reliably as a direct one. In a latency-bound loop, the call overhead then hides in the shadow of the critical chain. std::function is consistently about 15% slower; type erasure adds another level of indirection on top of the call through the stored function pointer. The lesson is not “virtual calls are free”, but “measure on your target before you trade readability for a folk-wisdom speed-up”. A template is still the cleanest way to express a choice that is fixed at compile time, and it lets the compiler optimize across the call.
Getting Around the Wall: More Channels¶
If a single loop is limited by its own chain, the way to use the rest of the core is to give it independent chains. A single Costas loop has only one, but receivers often run many loops side by side: one per channel after a channelizer, one per antenna, one per tracked signal. Put several of them in the same inner loop, and the out-of-order core will overlap their chains:
for (std::size_t i = 0; i < n; ++i) {
for (std::size_t k = 0; k < K; ++k) { // K independent dependency chains
const cf32 nco(std::cos(-phase[k]), std::sin(-phase[k]));
const cf32 y = cmul(in[k][i], nco);
out[k][i] = y;
const float error = y.real() * y.imag();
freq[k] += beta * error;
phase[k] += freq[k] + alpha * error;
if (phase[k] >= two_pi) phase[k] -= two_pi;
else if (phase[k] < 0) phase[k] += two_pi;
}
}
channels K |
ns per sample per channel |
total MS/s |
throughput gain |
|---|---|---|---|
1 |
20.8 |
48 |
1.0x |
2 |
10.7 |
94 |
1.9x |
4 |
6.5 |
154 |
3.2x |
8 |
4.2 |
240 |
5.0x |
Apple M1 performance core, Apple Clang 21, -O3 -mcpu=native.
Two channels cost no more than one, and eight channels interleaved in one thread process 240 million samples per second in total, five times the single-loop rate, on one core, with no SIMD intrinsics and no threads. This is the most important design lesson of this chapter: when the algorithm has a feedback loop, look for parallelism across channels instead of within the loop. It is also exactly how hardware designers think: an FPGA implementation of eight Costas loops would time-multiplex them through one pipelined datapath, eight samples in flight at once, for the very same reason.
Key Takeaways¶
Feedback loops (PLL, Costas, timing recovery, AGC, IIR) cannot be vectorized by NumPy. Moving them to C++ gives the largest speed-ups in this book so far: 86 times over PySDR’s code as written, ten times over carefully tuned pure Python.
Their speed is limited by the latency of the feedback chain, not by the amount of arithmetic. Shorten the chain, and do not add work to it.
“Branchless” code lengthens the chain. A branch that is almost never taken is better left as a branch.
Run-time dispatch (switch, function pointer, virtual call) costs next to nothing in such a loop on a modern core;
std::functioncosts a little more. Measure before trading clarity for speed.To go faster, process independent channels interleaved: eight Costas loops in one thread ran five times faster in total than one.