34. Appendix: Measuring Before Optimizing

Some chapters in this book make claims like “this version is three times faster”. Such claims are only worth something if the measurement behind them is sound, and measuring the speed of code turns out to be surprisingly easy to get wrong. This appendix builds a small benchmark harness, shows three ways a benchmark can lie to you (with real numbers), and then looks at the question that matters most for a receiver: not how fast the code is on average, but whether it finishes on time, every time.

Fedor Pikus opens his book on efficient programs with the rule that sums up this chapter: never guess about performance (The Art of Writing Efficient Programs, Packt 2021, chapter 2). Measure, and then make sure the measurement measures what you think it does.

The Units We Use

For streaming DSP the natural unit is nanoseconds per sample. It connects directly to the real-time budget from the Introduction: at 20 MS/s you have 50 ns per sample, so a filter that costs 13 ns per sample uses about a quarter of one core. Its inverse, megasamples per second (MS/s), is the highest sample rate one core could sustain if it did nothing else. When a benchmark processes a block of \(B\) samples per call, we divide the time per call by \(B\).

Two more words we will use carefully: throughput is how many samples per second the code can process when it runs flat out; latency is how long one particular sample (or block) takes from arrival to result. A design can have great throughput and terrible latency (process huge blocks), or the other way round.

Correct Before Fast

The first rule of benchmarking DSP code is that the code under test must be correct, and you have to check that, not assume it. An off-by-one in a delay line still produces plausible-looking noise at high speed. Every benchmark in this book has a test next to it that runs first. Two kinds of test pay for themselves again and again:

  • Hand vectors, inputs whose correct output you can work out on paper: an impulse into an FIR filter must return its taps; an oscillator at a quarter of the sample rate must produce exactly \(1, j, -1, -j\).

  • A reference implementation, as simple as possible and in higher precision (double, or the original Python), compared against the optimized version on realistic random input. For streaming code, feed the input in blocks of random size: that is how you catch state that is not carried correctly across block boundaries.

In the Feedback Loops: the Costas Loop chapter, for example, the C++ port of PySDR’s Costas loop is compared sample by sample with the NumPy original, and agrees to \(2.4 \cdot 10^{-15}\).

A Small Benchmark Harness

There are excellent benchmark libraries (Google Benchmark is the most popular in C++), and you should use one in a real project. For a book, though, a hundred lines you can read top to bottom teach more. Our harness is code/include/cppsdr/bench.hpp. Its core does four things:

template <class F>
result run(std::string name, std::size_t items_per_call, F&& f,
           double min_seconds = 0.25, int min_samples = 25)
{
    using clock = std::chrono::steady_clock;

    // 1) Warm up: fault in pages, train branch predictors, ramp the clock up.
    auto warm_until = clock::now() + std::chrono::milliseconds(50);
    while (clock::now() < warm_until) f();

    // 2) Batch calls so one timing sample lasts >= 1 ms; timer overhead vanishes.
    std::size_t batch = 1;
    for (;;) { /* double batch until one batch takes > 1 ms */ }

    // 3) Collect many timing samples...
    // 4) ...and report the median (robust) and the minimum.
}

It uses std::chrono::steady_clock, which never jumps (unlike the wall clock, which can be adjusted while you measure). It reports the median of many timing samples, which is robust against the occasional interruption, rather than the mean, which a single long interruption can drag around. And on Apple Silicon it asks the operating system to prefer the performance cores, because a benchmark that lands on an efficiency core runs at a fraction of the speed.

Each benchmarked function is wrapped in a lambda, and that is where the first trap lies.

Three Ways a Benchmark Lies

The Work That Never Happened

Here is a benchmark of a function that computes the average power of a block of 4096 samples:

bench::run("power(), result discarded", N, [&] { (void)power(x); });

It reports 0.0 ns per call. The compiler inlined power(), noticed that its result is never used and that it has no side effects, and deleted the whole computation. We benchmarked an empty loop. The fix is to make the result observable:

template <class T>
inline void do_not_optimize(T const& value)
{
    asm volatile("" : : "r,m"(value) : "memory");
}

bench::run("power(), result kept", N, [&] {
    float p = power(x);
    bench::do_not_optimize(p);
});

The empty asm volatile statement emits no instruction at all, but the compiler must assume that it reads value (and, because of the "memory" clobber, any memory), so the computation has to happen. Now the benchmark reports 4.0 µs per call, about 1 ns per sample. Google Benchmark’s benchmark::DoNotOptimize is the same trick.

The Work That Happened at Compile Time

The second trap is the mirror image. A loop that sums the numbers 1 to 4096 reported 0.3 ns, because the input was a compile-time constant and the compiler computed the answer, 8 390 656, while compiling. Real samples come from an ADC at run time, so benchmark inputs must too: fill them from a random generator or a file, never from constants the compiler can see.

The Work That Depends on Where It Lives

The third trap is subtler and cannot be fixed with one line. The Costas loop of the Feedback Loops: the Costas Loop chapter ran at 30 ns per sample in one build of a benchmark program, and at 24.6 ns after an unrelated change elsewhere in the same program, with identical source code for the loop. Nothing was wrong with either measurement; each was stable from run to run. What differed was everything around the loop: the other functions linked into the program, and therefore the addresses at which the loop’s instructions and data ended up. Tight loops whose speed is limited by a chain of dependent instructions are sensitive to such layout details. Mytkowicz, Diwan, Hauswirth and Sweeney showed in a widely cited paper that even the size of the environment variables or the link order can bias measurements enough to reverse a conclusion (“Producing Wrong Data Without Doing Anything Obviously Wrong!”, ASPLOS 2009, doi:10.1145/1508244.1508275).

The practical consequence: when two variants differ by only a few percent, compare them in the same binary, run them interleaved (A, B, C, A, B, C, …) for several rounds, and report the spread. code/bench/bench_costas_variants.cpp does exactly that. Large differences (a factor of two, or of seventy) do not need that much care; small ones do.

Note

Two more effects that can matter on other systems, though they were small on the M1 used here: the very first call to a function is often slower (pages of freshly allocated memory have to be mapped by the OS, caches and branch predictors are cold), and CPUs with aggressive frequency scaling may need a few milliseconds of load before reaching full speed. The warm-up phase of the harness takes care of both. Measured here, the first call of a 1-million-sample FIR run took 12.3 ms against 11.5 to 11.9 ms for the following calls, an effect of a few percent.

Looking Under the Hood

When a number surprises you, look at what the compiler actually generated. Three tools carried most of the weight in this book:

  • Compiler Explorer shows the assembly for a snippet with any compiler and flags, side by side. Ideal for “does this loop vectorize?”.

  • objdump -d --disassemble-symbols=<name> file.o does the same for your own object files. Counting instruction types (vector fmla.4s versus scalar fadd) is often enough to explain a factor of three.

  • A sampling profiler answers “where does the time go?” for a whole program: perf record / perf report on Linux (Pikus, chapter 2, walks through it), Instruments or the sample command on macOS. Build with -O3 -g: profile the optimized code, with symbols.

Pikus also recommends llvm-mca, which simulates how a CPU pipeline would execute a piece of assembly; it is the right tool when you want to understand why a loop needs a certain number of cycles per iteration.

Averages Hide the Tail

So far we have measured how fast code runs when it runs flat out. A receiver has a different question: will every block be processed before the next one arrives? For that, the median is the wrong statistic. We need the whole distribution, especially its tail.

Let’s time 200 000 individual calls of a 64-tap FIR filter on 1024-sample blocks. To see whether a careless heap allocation matters, each iteration also runs a second version of the same work that copies the block into a freshly allocated std::vector first; the two versions run interleaved, so whatever the operating system does hits both equally:

Table 34.1 Time per 1024-sample block in µs, 200 000 blocks, ordinary thread on macOS

Variant

median

p99

p99.9

p99.99

max

preallocated buffers

11.1

12.8

23.2

76.1

211

std::vector allocated per block

11.3

13.0

22.3

53.9

546

(p99.9 means: 99.9% of the blocks were faster than this.) Two things stand out. First, the allocation makes no reliable difference here: about 1.5% at the median, and in the tail the two variants trade places from one run to the next (in an earlier run the allocating version had the worse p99.99). The macOS allocator serves small blocks from a fast per-thread cache. That does not make it safe: an allocator can take a lock or ask the kernel for memory, and when it does is out of your control. Ross Bencina’s rules for real-time audio code (no allocation, no locks, no file or network I/O, nothing with unbounded execution time on the real-time thread) are about the worst case, not the average. Second, and more important: even the clean version has a tail. One block in ten thousand took seven times the median, and the slowest took nineteen times as long. The code did not change between those blocks. The operating system did something else in the meantime.

On Time, Every Time: the Scheduler

A real receiver does not run flat out. It waits until a block of samples has arrived, processes it, and waits again. code/bench/bench_rt_jitter.cpp simulates exactly that: a block of 2048 samples arrives every 100 µs (20.48 MS/s), the thread sleeps until the block is due, filters it (about 22 µs of work), and goes back to sleep. We record how late the thread wakes up and count a deadline miss whenever a block is not finished before the next one is due. Each run lasts 20 seconds, 200 000 blocks, in three configurations:

  • default scheduling: an ordinary thread;

  • QoS user-interactive: macOS’s highest “quality of service” class, a hint that the work is important;

  • time-constraint policy: the real-time scheduling class macOS uses for Core Audio’s I/O threads. The thread declares its period (100 µs), how much CPU time it needs per period (60 µs) and its deadline, and the scheduler promises to run it accordingly.

thread_time_constraint_policy_data_t pol;
pol.period      = ns_to_ticks(100'000);  // a block every 100 us
pol.computation = ns_to_ticks(60'000);   // needs up to 60 us of CPU per period
pol.constraint  = ns_to_ticks(100'000);  // must be done within the period
pol.preemptible = 1;
thread_policy_set(mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY,
                  reinterpret_cast<thread_policy_t>(&pol),
                  THREAD_TIME_CONSTRAINT_POLICY_COUNT);
Wake-up lateness percentiles for default, QoS and real-time thread policies

Figure 34.1 How late a periodic thread wakes up, as percentiles over 200 000 periods of 100 µs (log scale).

Table 34.2 Periodic 100 µs task with 22 µs of work, 200 000 periods each

Scheduling

deadline misses

wake-up late, median

p99.99

max

default

1 448

17.7 µs

459 µs

1.06 ms

QoS user-interactive

2 237

18.4 µs

755 µs

3.14 ms

time-constraint (real-time)

4

2.4 µs

38.7 µs

0.41 ms

Apple M1, macOS, desktop session with ordinary background activity. A second run gave 5 617 and 483 misses for the first two rows, and 7 for the real-time policy.

The filter code is identical in all three runs, and so is its median work time (about 22 µs). What differs is when it gets to run. With ordinary scheduling, the thread wakes up 18 µs late in a typical period and sometimes more than a millisecond late, ten whole periods, and between 0.7% and 2.8% of the blocks miss their deadline. The non-real-time numbers also changed a lot from run to run, because they depend on whatever else the machine happens to be doing. With the real-time policy, the median wake-up delay drops to 2.4 µs, 99.99% of the periods start within 39 µs, and only 4 of 200 000 blocks were late. We also tried spinning in a loop instead of sleeping. That removes the wake-up delay itself, but the thread can still be pre-empted, and it still missed 306 deadlines while burning a whole core.

This is the strongest argument for C++ in this chapter, and notice that it is not about speed at all. A real-time thread only helps if everything it does has bounded execution time: a real-time thread that takes a lock held by an ordinary thread, waits for the garbage collector, or calls into the allocator at the wrong moment is back to square one. C++ lets you write code where you can see and control every one of those things. On Linux the equivalent tools are SCHED_FIFO priorities (via pthread_setschedparam, which needs the right privileges), the PREEMPT_RT kernel, and dedicating cores to the real-time work; the same benchmark tries SCHED_FIFO there. Real systems combine all of this with enough buffering to ride out the rare late wake-up: the 0.41 ms worst case above is four periods, so a receiver with a few blocks of buffer would not have lost a single sample.

Key Takeaways

  • Test for correctness first, with hand vectors and a simple reference, and feed streaming code random block sizes.

  • Make benchmark results observable (do_not_optimize) and benchmark inputs unknown to the compiler.

  • Report medians, use enough repetitions, and compare small differences interleaved within one binary; code layout alone can move a tight loop by 20%.

  • For real-time work, look at percentiles and deadline misses, not averages. On a general-purpose OS the scheduler, not your code, dominates the tail, and a real-time scheduling policy plus code without unbounded operations is what fixes it.