Real-Time Deterministic C++

A car follows another car. Its control loop must finish every 10 ms. Most cycles take 4 ms, so the average looks safe. One slow cycle in a hundred is enough to make the car lurch.

Watch the bars under the road: one bar per cycle, with the deadline drawn across. Switch on one hazard, such as allocating memory on the hot path. Most bars stay short, a few cross the line, and the follower lurches. Then we build, piece by piece, the C++ habits that keep every cycle on time.

You need some C++, or another typed language, and loops, arrays and pointers. We build the rest from zero.

Miss a beat

Ready

Collecting cycles.

Toy timing model, not a measurement. The 10 ms period is typical of a control loop, and every hazard's cost is illustrative. A crowd passes every few seconds. When a cycle is late, the car's actuator gets no fresh command, falls back to gentle braking, then catches up: that is the lurch. Body pitch is drawn larger than life so you can see it.

Chapter 0

The average is the wrong number

See why a loop that is fast on average can still fail, and which numbers tell the truth

You sit in a car on the motorway with the cruise control set to follow the truck ahead. A small computer reads the radar, decides how hard to brake or accelerate, and sends one command. Then it does it again. And again, a hundred times a second.

Each repeat is one cycle: read the inputs, compute, write the output. The software that runs every cycle is the hot path. The time between the start of one cycle and the start of the next is the period. Here it is 10 ms, a typical figure for a control loop.

The output of each cycle must be ready before the next one starts. That moment is the cycle's deadline. A late command is not a slow command. It is a missing command. The brakes act on the last value they had.

Now the trap. You time the loop on your desk. It averages 5 ms. Half the budget is spare, so you ship it. But the average says nothing about the slowest cycles, and the slowest cycles are the ones that hurt.

Same average, different worst

Each bar is one cycle, 300 of them, with the 10 ms deadline across. All three loops average about 5 ms. Pick each one and read the worst cycle and the misses.

Toy samples from three seeded distributions. Statistics in the read-out come from 1,000 samples of each loop; the canvas shows the first 300.

Three words name what you just saw. Jitter is how much the cycle time varies from cycle to cycle. The tail is the rare, slow end of the distribution. Tail latency is a number that describes that end, such as the 99th percentile or the maximum.

Real-time software is judged on its tail. A real-time system is one where a correct answer delivered late counts as a wrong answer. "Real-time" does not mean fast. It means on time, every time.

How often is "rare"?

Rare per cycle is not rare per hour. Count the cycles first.

misses per hour = p × f × 3600
misses per hour
how many cycles finish after their deadline in one hour of running
p
the fraction of cycles that miss, for example 0.001 for one in a thousand
f
the loop rate in cycles per second, 1 / period: 100 for a 10 ms period

Work it for one miss in a thousand cycles at 100 cycles a second.

cycles per hour = 100 × 3600 = 360,000  ·  misses = 0.001 × 360,000 = 360 per hour

That is one late command every ten seconds. A test drive of five minutes would show about 30 of them, if anyone looked. Most teams only look at the average.

The average hides them for a simple reason. Take 1,000 cycles: 990 at 4 ms and 10 at 25 ms.

mean = (990 × 4 + 10 × 25) / 1000 = (3960 + 250) / 1000 = 4.21 ms  ·  max = 25 ms

The ten bad cycles move the mean by only 0.21 ms. Every one of them is two and a half times over the deadline.

What the loop looks like in C++

Here is the skeleton of a periodic loop. Two details matter. It uses steady_clock, which never jumps when someone sets the wall clock. And it wakes at absolute times, start plus k periods, so one slow cycle does not push every later cycle back. It also counts its own misses.

#include <chrono>
#include <cstdint>
#include <thread>

using Clock = std::chrono::steady_clock;   // never jumps when the wall clock is set
using namespace std::chrono_literals;

struct LoopStats {
  std::int64_t cycles = 0;
  std::int64_t missed = 0;                 // cycles that finished after their deadline
  Clock::duration worst{0};                // the longest single cycle seen
};

// Runs step() every period until it returns false. Wakes on ABSOLUTE times
// (start + k * period), so a slow cycle does not push every later cycle back.
template <typename Step>
LoopStats runPeriodic(Step&& step, Clock::duration period) {
  LoopStats s;
  auto next = Clock::now() + period;
  for (;;) {
    const auto t0 = Clock::now();
    const bool more = step();
    const auto t1 = Clock::now();
    ++s.cycles;
    if (t1 - t0 > s.worst) s.worst = t1 - t0;
    if (t1 > next) {                        // we finished after this cycle's deadline
      ++s.missed;
      while (next < t1) next += period;     // skip the slots we lost; do not burst
    }
    if (!more) break;
    std::this_thread::sleep_until(next);    // sleep to the next absolute release
    next += period;
  }
  return s;
}

Notice what happens after a miss. The loop skips the slots it lost instead of running several cycles back to back to "catch up". A burst of catch-up cycles would send the actuator a flurry of stale commands. Skipping and counting is the honest choice.

Failure: "it passed every test"

A team times its loop on a laptop with an idle scene and reports a 4 ms average. On the vehicle, the driver feels a jolt every few minutes. Diagnose it with three steps. First, log every cycle's time on the target, not a sample. Second, report the maximum and the 99.9th percentile next to the mean. Third, line up the slow cycles with what else happened then: a crowd in the scene, a log file rolling over, another process waking up.

The whole lesson in one line. Real-time C++ removes every source of a surprise pause from the hot path: no heap, no unbounded loops, no waiting on slow threads, no data layout that starves the cache, no exceptions. Then it measures the tail to prove it.

This is the daily work of a perception onboard software lead at a robotics or vehicle company. Around the learned models sits a layer of classical C++: tracking, fusion, monitors, emergency braking. It must run on time every cycle, with fixed memory, and give the same answer for the same input. Here is the road.

  1. What a deadline is: period, deadline, worst-case execution time, latency budgets, hard and soft deadlines.
  2. Where time hides: computation, memory and waiting; the mean, the p99 and the max.
  3. No allocation after start-up: why the heap is unpredictable; pools, arenas and fixed vectors. This is the hero's first switch.
  4. Data layout and the cache: cache lines, array of structs against struct of arrays, false sharing. The third switch.
  5. Bounded work: fixed capacities, capped inputs, and what to drop when the scene overflows. The fourth switch.
  6. Threads without waiting: priority inversion and a lock-free ring buffer. The second switch.
  7. Same input, same output: the sources of nondeterminism and how to make a run replayable.
  8. Errors without surprises: error codes, expected-style results, and what to do when a check fails in flight.
  9. Proving it stays fast: tail measurement, sanitizers, static analysis and CI budgets.
  10. The cycle bench: compose a perception cycle, load the scene, inject hazards. Break it on purpose.
  11. Interview arsenal: cheat sheet, design prompts, drills and debugging scenarios.
An interviewer asks: "Your loop averages 4 ms against a 10 ms deadline. Is it real-time safe?"

Chapter 1

What a deadline is

Name the four times every real-time task has, and split one frame's time between its stages

A camera on the windscreen takes 30 pictures a second. Each picture travels through a chain of software: a learned model finds objects, a tracker follows them, a monitor checks them, and the result goes to the brakes. A new picture arrives every 33.3 ms, whether the chain is ready or not.

Four times describe any job like this. Learn them once and every real-time discussion gets easier.

  1. The release time is when the job may start: the moment the picture arrives.
  2. The period T is the time between two releases: 33.3 ms here.
  3. The deadline D is when the result must be ready, measured from the release. It is often equal to T, sometimes shorter.
  4. The execution time C is how long the job computes. It changes from frame to frame. Its largest possible value is the worst-case execution time, or WCET.

One more: the job may not start the instant it is released. An interrupt, another task, or the operating system can hold it back. That start delay is the release jitter J. The time from release to finish is the response time R.

Fit the job in its window

Each block is one job. Arrows mark releases, warm ticks mark deadlines. Job 4 gets the worst start delay and the worst execution time at once. Raise C or J until it misses, then switch between hard and soft.

33 ms
100%
20.0 ms
3.0 ms

Toy timeline: each job's execution time is drawn between 60% and 100% of C, and its start delay between 0 and J; job 4 gets both maxima. A job that overruns into the next period delays the next release in this toy; real schedulers differ.

Two equations a lead uses every week

The first says how busy the processor is. The second says whether the worst job still finishes in time.

U = C / T      R = J + C ≤ D
U
utilisation: the fraction of the processor this task uses in the worst case. Above 1, it cannot keep up
C
the worst-case execution time of one job, in ms
T
the period: the time between two releases
R
the worst-case response time: from release to finish
J
the worst start delay after release (release jitter)
D
the deadline, measured from the release

This simple R holds for one task alone on its processor. With several tasks sharing a processor, R also includes the time that higher-priority tasks take. Response-time analysis adds those up; the RTOS lesson shows the scheduler side.

A latency budget, worked

The chain from camera to brake must fit in one frame. A latency budget gives each stage a slice of that time. Here is an illustrative split for the 30 Hz camera.

period T 33.3 ms perception model 15.0 ms tracking 5.0 ms fusion 3.0 ms runtime monitor 2.0 ms transport 4.0 ms sum of budgets 29.0 ms slack = 33.3 − 29.0 = 4.3 ms (13% of the period)

Uchain = 29.0 / 33.3 = 0.87  ·  slack = 4.3 ms  ·  rule: keep at least 10%, so 3.3 ms

The slack is not waste. It absorbs the things you did not measure: a cache that was cold, an interrupt storm, a scene busier than any in your logs. A budget with zero slack is a budget that will be missed.

You can make the compiler hold you to the budget. Write the plan as constexpr data and check it with static_assert. If someone raises a stage budget so the sum no longer fits, the build fails.

#include <array>

// A latency budget written as code, so the build fails if the plan stops adding up.
// Every number is in microseconds and is illustrative: measure your own stages.
struct Stage { const char* name; int budget_us; };

constexpr int kPeriodUs = 33'333;          // a 30 Hz camera: one frame every 33.3 ms
constexpr std::array<Stage, 5> kStages{{
    {"perception model", 15'000},
    {"tracking",          5'000},
    {"fusion",            3'000},
    {"runtime monitor",   2'000},
    {"transport",         4'000},
}};

constexpr int totalBudget() {
  int sum = 0;
  for (const Stage& s : kStages) sum += s.budget_us;   // constexpr loop: runs at compile time
  return sum;
}

constexpr int kSlackUs = kPeriodUs - totalBudget();

static_assert(totalBudget() <= kPeriodUs, "stage budgets exceed the frame period");
static_assert(kSlackUs >= kPeriodUs / 10, "keep at least 10% of the period as slack");

Hard, firm and soft

Not every deadline costs the same when missed.

The class decides the design. Hard paths get analysed worst cases and fixed resources. Soft paths can use averages and adapt. Mixing them on one thread is a classic mistake: the soft path's spikes land on the hard path.

Failure: the WCET that was really a "typical" time

A stage gets a 5 ms budget from a benchmark on a quiet desk scene. In a busy junction it takes 9 ms. Diagnose it by asking where the WCET came from. A measured WCET is the largest time seen in tests, so it is only as good as the worst test. Find the inputs that drive the work, such as object count, and test at their maximum. On modern processors with caches, a proven WCET from static analysis is hard to get, so teams combine worst-case inputs, long soak tests and a margin.

An interviewer asks: "A task has period 20 ms, deadline 20 ms, WCET 15 ms and a worst start delay of 6 ms. Does it meet its deadline?"

Chapter 2

Where time hides

Split a cycle's time into computation, memory and waiting, and read the tail from a histogram

A tracker runs at 4 ms most cycles. Once every few seconds it takes 15 ms. The code is the same in both cycles, so where did the extra 11 ms go? A slow cycle is never slow for no reason. The time went somewhere, and you can find it.

Every millisecond of a cycle goes to one of three things.

  1. Computation: the processor executes your instructions. This grows with the work: more objects, more pairs to compare.
  2. Memory: the processor waits for data. A read from the processor's small, fast cache costs on the order of a nanosecond. A read that misses the cache and goes to main memory costs on the order of a hundred nanoseconds.
  3. Waiting: your thread is not running at all. It waits for a lock, for the operating system, for a page of memory, or for a higher-priority task.

The three causes leave different fingerprints. Computation scales with the input. Memory stalls get worse when the data grows past the cache or when another program evicts it. Waiting shows up as rare, long spikes that do not depend on the input at all.

Read the tail

The histogram counts 5,000 cycles. Three sliders set the three causes. Watch which marker moves: the mean, the p99 or the max. The bars below split the typical cycle and the slowest cycle by cause.

3.0 ms
8,000
0.0%

Toy model: computation varies by ±10%; each cache miss costs 100 ns, the miss count varies, and 1% of cycles see three times the misses (another program evicted the cache); a lock wait lasts 2 to 18 ms. The bar heights use a log scale so the rare slow cycles stay visible. Real numbers depend on your processor and must be measured.

CauseFingerprint in the dataFirst tool to reach for
Computationcycle time rises with object count; the histogram shifts as a wholesampling profiler, stage timers against input size
Memorya wider spread; worse when data grows or a neighbour runs; same code, same input, different timehardware performance counters for cache misses
Waitingrare, long spikes unrelated to input; wall time jumps while CPU time does notscheduler tracing, lock statistics

Percentiles, from zero

Sort all the cycle times from fastest to slowest. The p-th percentile is the time that p percent of cycles beat. The median is p50; p99 is the time that 99% of cycles beat; the maximum is the slowest cycle of all.

tq = the sample at rank ⌈ q × n ⌉ in sorted order
tq
the q-quantile of the cycle times, for example t0.99 = p99
q
the fraction, between 0 and 1: 0.5 for the median, 0.99 for p99, 0.999 for p99.9
n
the number of cycles measured

Use the 1,000 cycles from Chapter 0 again: 990 at 4 ms, then 10 at 25 ms, sorted.

p50: rank 500 → 4 ms  ·  p99: rank 990 → 4 ms  ·  p99.9: rank 999 → 25 ms  ·  max: rank 1000 → 25 ms

Look at p99. It still says 4 ms, because exactly 1% of cycles are slow. The p99.9 and the max see them. For a 100 Hz loop, p99 ignores one cycle every second. That is why real-time teams report p99.9, p99.99 and the max, not just p99.

Measure before guessing

Engineers guess wrong about where time goes. Measure first, on the real target, with the real load.

The histogram below is how a real system can keep measuring in the field. It has fixed buckets, so recording is a divide, an increment and a compare. It never allocates, so it is safe on the hot path.

#include <array>
#include <cstdint>

// A latency histogram with fixed buckets: recording costs a few instructions
// and never allocates, so it can stay switched on in the real system.
class LatencyHistogram {
 public:
  static constexpr int kBuckets = 400;       // 0 .. 39.9 ms in 100 us steps
  static constexpr std::uint32_t kStepUs = 100;

  void record(std::uint32_t us) {
    const std::uint32_t b = us / kStepUs;
    ++counts_[b < kBuckets ? b : kBuckets - 1];   // the last bucket holds every overflow
    if (us > max_us_) max_us_ = us;               // keep the true maximum separately
    sum_us_ += us;
    ++n_;
  }

  // Upper edge of the bucket that holds the q-quantile, e.g. q = 0.99 for p99.
  std::uint32_t percentileUs(double q) const {
    if (n_ == 0) return 0;
    const std::uint64_t rank = static_cast<std::uint64_t>(q * static_cast<double>(n_ - 1)) + 1;
    std::uint64_t seen = 0;
    for (int b = 0; b < kBuckets; ++b) {
      seen += counts_[b];
      if (seen >= rank) return static_cast<std::uint32_t>(b + 1) * kStepUs;
    }
    return max_us_;
  }

  double meanUs() const { return n_ ? static_cast<double>(sum_us_) / static_cast<double>(n_) : 0.0; }
  std::uint32_t maxUs() const { return max_us_; }

 private:
  std::array<std::uint32_t, kBuckets> counts_{};  // zeroed: no uninitialised counts
  std::uint64_t sum_us_ = 0, n_ = 0;
  std::uint32_t max_us_ = 0;
};

Two design choices matter here. The last bucket collects every overflow, so nothing is lost. And the true maximum is kept separately, so a 300 ms freak cycle is reported as 300 ms, not as "over 40".

Failure: the profiler says it is fine

A team profiles the tracker and finds no hot function. Yet cycles spike to 18 ms. The profiler samples where the program runs, and a waiting thread does not run. Diagnose it by comparing two clocks per cycle: wall time from steady_clock and the thread's own CPU time. If wall time jumps while CPU time does not, the thread was waiting. Then trace the scheduler to see who held the processor or the lock.

An interviewer asks: "Your cycle-time p99 is 5 ms against a 10 ms deadline, but the vehicle logs show missed deadlines. How can both be true?"

Chapter 3

No allocation after start-up

See why asking for memory mid-cycle is a gamble, and replace it with pools and arenas sized up front

A tracker creates a new track whenever a new object appears. The obvious code is tracks.push_back(t) on a std::vector. It works on every test. Then, on the road, a cyclist appears at the exact moment the vector is full. The vector asks for a bigger block of memory, copies every track across, and frees the old block. That one cycle takes ten times longer than the one before.

Memory you ask for while the program runs comes from the heap. The code that hands it out is the allocator: new, malloc, and every container that grows. On a desktop it is fast on average. On the hot path its cost is a gamble, for four reasons.

  1. It searches. A general allocator keeps lists of free blocks of many sizes. Finding a fit can take a few steps or many.
  2. It fragments. After many allocations and frees of different sizes, the free memory is split into small holes. A large request may fail, or force a slow path, even when plenty is free in total.
  3. It shares. Several threads use the same heap, so the allocator may take a lock. Your hard real-time thread can end up waiting for a logging thread.
  4. It asks the operating system. When the heap runs low, the allocator requests more pages. The first touch of a new page causes a page fault: the operating system stops your thread to map real memory. That can cost far more than the allocation itself.

Watch the heap fragment

The strip is 48 cells of memory. Each step either asks for a block or frees one. In heap mode the blocks have different sizes and the allocator searches for the first hole that fits. Run 100 steps, then switch to the pool.

Toy allocator: first fit over a 48-cell strip, requests of 1 to 7 cells, frees chosen at random from live blocks, seeded. Real allocators use size classes and are much smarter, but they still search, split, merge and sometimes call the operating system.

Measuring fragmentation

The device reports how broken the free memory is. One number captures it.

F = 1 − L / S
F
external fragmentation: 0 when all free memory is one block, close to 1 when it is many small holes
L
the largest free block, in cells (or bytes)
S
the total free memory, in the same unit

Say 19 cells are free, but the largest hole is 5 cells.

F = 1 − 5 / 19 = 1 − 0.26 = 0.74  ·  a request for 6 cells fails although 19 are free

The growing vector, counted

Suppose a vector doubles its capacity each time it fills. Many standard libraries grow by a factor of 1.5 or 2. Push 1,000 tracks into an empty vector with doubling.

capacity after each growth: 1 2 4 8 16 32 64 128 256 512 1024 allocations 11 elements copied in total 1 + 2 + 4 + ... + 512 = 1,023 the single worst push_back copies 512 elements and frees the old block

The average push is cheap: about one copy each. The worst push copies 512 tracks. That is the shape of every heap problem: a fine average with a terrible tail.

The rule, and the three tools

The rule is short: allocate everything at start-up, then never again. At start-up you size every container for the worst case. You touch every page, so no page fault waits for later. On Linux you lock the memory with mlockall, so the operating system cannot swap it out. After that, the hot path uses three tools.

ToolAllocateFreeFragments?Best for
General heapsearch, variesmerge, variesyesstart-up only
Poolpop a free list, O(1)push it back, O(1)noobjects of one type that come and go: tracks
Arenabump a pointer, O(1)all at once, per cyclenoscratch data that lives one cycle
Fixed vectorplace at the end, O(1)from the end, O(1)nobounded lists: detections, candidates

Here is a pool from scratch. It uses a free list: each free slot stores the index of the next free slot, so finding a free slot is one array read. Objects are built in place with placement new, which constructs an object in memory you already own.

#include <cstddef>
#include <new>
#include <utility>

// A fixed pool of N objects of type T. All memory is inside the pool object,
// reserved at start-up. create and destroy are O(1) and never call the heap.
template <typename T, int N>
class Pool {
 public:
  Pool() { for (int i = 0; i < N; ++i) next_[i] = i + 1; }   // free list 0 -> 1 -> ... -> N
  ~Pool() { for (int i = 0; i < N; ++i) if (live_[i]) destroy(i); }
  Pool(const Pool&) = delete;              // copying would duplicate live objects
  Pool& operator=(const Pool&) = delete;

  // Builds a T in a free slot. Returns its handle, or -1 if the pool is full.
  template <typename... Args>
  int create(Args&&... args) {
    if (head_ == N) return -1;             // full: the caller decides what to drop
    const int h = head_;
    head_ = next_[h];                      // pop the free list
    ::new (static_cast<void*>(slot_[h].bytes)) T(std::forward<Args>(args)...);
    live_[h] = true;
    return h;
  }

  T* get(int h) {                          // nullptr for a bad or dead handle
    if (h < 0 || h >= N || !live_[h]) return nullptr;
    return std::launder(reinterpret_cast<T*>(slot_[h].bytes));
  }

  void destroy(int h) {
    T* p = get(h);
    if (!p) return;                        // double free is caught, not undefined
    p->~T();
    live_[h] = false;
    next_[h] = head_;                      // push the slot back on the free list
    head_ = h;
  }

 private:
  struct Slot { alignas(T) unsigned char bytes[sizeof(T)]; };  // raw, correctly aligned
  Slot slot_[N];
  int  next_[N];
  bool live_[N] = {};
  int  head_ = 0;
};

Three details make it safe. The raw bytes are alignas(T), so any type sits at an address it is allowed to live at. The pool hands out integer handles instead of pointers, so a stale handle can be checked against live_ instead of crashing. And std::launder tells the compiler that a new object now lives in those bytes.

The arena suits data that lives for exactly one cycle: scratch arrays, candidate lists, temporary matrices.

#include <cstddef>
#include <cstdint>
#include <new>
#include <type_traits>

// A per-cycle arena: a bump pointer over a buffer reserved at start-up.
// Allocation is an add and a compare. reset() frees everything at once,
// at the end of each cycle, so there is no per-object free and no fragmentation.
class CycleArena {
 public:
  CycleArena(unsigned char* buf, std::size_t size) : buf_(buf), size_(size) {}

  // align must be a power of two. Returns nullptr when the cycle's budget is spent.
  void* alloc(std::size_t bytes, std::size_t align) {
    const std::uintptr_t base = reinterpret_cast<std::uintptr_t>(buf_);
    const std::uintptr_t p = (base + used_ + (align - 1)) & ~(std::uintptr_t)(align - 1);
    const std::size_t end = static_cast<std::size_t>(p - base) + bytes;
    if (end > size_) return nullptr;       // over budget: report it, never grow
    used_ = end;
    if (used_ > high_water_) high_water_ = used_;
    return reinterpret_cast<void*>(p);
  }

  template <typename T>
  T* allocArray(std::size_t n) {
    static_assert(std::is_trivially_destructible_v<T>, "reset() runs no destructors");
    T* p = static_cast<T*>(alloc(n * sizeof(T), alignof(T)));
    if (p) for (std::size_t i = 0; i < n; ++i) ::new (static_cast<void*>(p + i)) T;  // start lifetimes
    return p;
  }

  void reset() { used_ = 0; }              // end of cycle: all of it is free again
  std::size_t highWater() const { return high_water_; }  // log this to size the buffer

 private:
  unsigned char* buf_;
  std::size_t size_, used_ = 0, high_water_ = 0;
};

Log the arena's high-water mark in testing and in the field. If the worst scene ever used 41 KB, a 64 KB arena has a clear margin, and you can say so in a design review.

Hidden allocations

The heap hides in places that do not say new. Check each of these on the hot path:

Chapter 9 shows a test that catches every one of them.

Failure: the jolt after twenty minutes

A system runs clean for twenty minutes, then shows a 30 ms spike every few minutes. Memory use climbs slowly. Diagnose it with an allocation counter on the hot path (Chapter 9). The usual cause is a container that grows a little in rare scenes, plus heap fragmentation that makes later requests slower. The fix is to find the container, reserve its worst case at start-up, and make it fixed-capacity.

An interviewer asks: "Why is a pool allocator better than new for track objects in a real-time tracker?"

Chapter 4

Data layout and the cache

Arrange data so each trip to memory brings back only what the loop needs

Picture a librarian who fetches books from a warehouse. Each trip takes ten minutes, and each trip brings back a whole shelf, not one book. If the books you need are on one shelf, one trip is enough. If each book is on a different shelf, you pay a trip per book.

The processor works the same way. Main memory is the warehouse. The cache is a small, fast store next to the processor. Memory moves between them in fixed chunks called cache lines, 64 bytes on most common processors. Read one float, and the whole 64-byte line around it comes along.

A read that finds its line already in the cache is a hit: on the order of a nanosecond. A read that does not is a miss: on the order of a hundred nanoseconds when it goes all the way to main memory. A loop that misses on every element can be a hundred times slower than one that hits.

Count the cache lines

A gating loop reads only x and y of every track. Each square is one 64-byte cache line; its fill shows how much of it the loop used. Switch the layout and drag the track count.

512

Illustrative: 100 ns per cold miss, 1 ns per hit, no hardware prefetching, so the times are an upper bound. Real processors prefetch sequential lines and hide much of this; the bytes moved still differ by the same factor.

Two layouts

An array of structs (AoS) keeps each track's fields together: x, y, velocity, covariance, id, all in one record. It is the natural way to write C++. A struct of arrays (SoA) keeps each field in its own array: all the x values together, all the y values together.

The best layout depends on the loop. The gating loop touches x and y of every track and nothing else. With AoS, every 64-byte record is one cache line, and the loop uses 8 bytes of it. With SoA, one line holds 16 x values, all of which the loop uses.

lines ≈ ∑streams ⌈ n × s / L ⌉
lines
the cache lines the loop brings in: an upper bound on cold misses
n
the number of tracks the loop visits
s
the stride: bytes from one element to the next in that stream (64 for an AoS record, 4 for a float array)
L
the cache-line size: 64 bytes on most common processors

Work it for 512 tracks.

AoS: 1 stream, ⌈512 × 64 / 64⌉ = 512 lines = 32 KB moved for 4 KB used

SoA: 2 streams, 2 × ⌈512 × 4 / 64⌉ = 2 × 32 = 64 lines = 4 KB moved

if every line were a cold miss: 512 × 100 ns = 51.2 µs against 64 × 100 ns = 6.4 µs

Eight times fewer lines. The real gap is smaller, because hardware prefetchers fetch the next lines of a steady stream early. But the AoS loop still moves eight times the bytes, and those bytes push other useful data out of the cache.

#include <atomic>
#include <cstdint>

// Array of structs: one 64-byte record per track. A loop that needs only
// x and y still drags every whole record through the cache.
struct TrackAoS {
  float x, y, vx, vy;                      // 16 bytes the gating loop needs
  float cov[10];                           // 40 bytes it does not need here
  std::uint32_t id, flags;                 //  8 bytes it does not need here
};
static_assert(sizeof(TrackAoS) == 64, "one record per typical 64-byte cache line");

// Struct of arrays: each field in its own array. The same loop now reads
// two dense arrays: 16 x values per cache line instead of one.
template <int N>
struct TracksSoA {
  float x[N], y[N], vx[N], vy[N];
  float cov[N][10];
  std::uint32_t id[N], flags[N];
};

template <int N>
int countInGate(const TracksSoA<N>& t, int n, float zx, float zy, float r2) {
  int hits = 0;
  for (int i = 0; i < n; ++i) {            // reads only t.x and t.y: dense, in order
    const float dx = t.x[i] - zx, dy = t.y[i] - zy;
    hits += (dx * dx + dy * dy <= r2);
  }
  return hits;
}

// False sharing: two threads write two counters on the same cache line, and
// the line bounces between cores. Aligning each counter to 64 bytes separates them.
struct alignas(64) PaddedCounter { std::atomic<std::uint64_t> n{0}; };
struct PerThreadStats { PaddedCounter perception, tracking; };  // one line each
static_assert(sizeof(PerThreadStats) == 128, "two counters, two cache lines");

The static_assert on the record size is a habit worth copying. If someone adds a field, the build tells them the record no longer fits one line, and the review can decide whether that matters.

False sharing

Caches keep a rule: only one core may write to a cache line at a time. If two threads on two cores write to two different variables that happen to share a line, the line bounces between the cores on every write. Neither thread shares any data with the other, yet both run slowly. This is false sharing.

Bounce the line

Two threads each increment their own counter. Watch the cache line travel. Then pad each counter to its own line.

Toy: the threads alternate writes. A line transfer between cores costs on the order of tens to a hundred nanoseconds on common processors; a write to a line the core already owns costs about a nanosecond.

The fix is layout again: give each thread's hot data its own line with alignas(64), as PaddedCounter does above. C++17 also names the size as std::hardware_destructive_interference_size, but not every standard library provides it yet, so many teams write 64 and check it per target.

Failure: two threads, twice the cores, half the speed

A team moves statistics counting to a second thread and the main cycle gets slower. Diagnose it with hardware performance counters: look for a high count of cache-line transfers between cores, often reported as coherence or "HITM" events, on the counter's address. Then print the addresses of each thread's hot variables. If two of them fall within the same 64 bytes, pad them apart.

An interviewer asks: "A gating loop reads x and y from 512 tracks of 64 bytes each. Why would struct of arrays help, and by roughly how much in memory traffic?"

Chapter 5

Bounded work

Give every loop a known maximum, and decide in advance what to drop when the world is busier than that

A car pulls into a stadium car park after a match. The radar sees 400 reflections: cars, people, barriers, lamp posts. On a quiet road it saw 30. The association step compares every track with every detection, so its work grows with the square of the count. Thirty objects is 900 comparisons. Four hundred is 160,000.

The cycle did nothing wrong. Its code is correct. It is simply not bounded: its work depends on the world, and the world has no upper limit. Real-time code must have a known maximum for every loop, set by the design, not by the scene.

Cap the crowd

The map shows detections around your car, seen from above. The chart shows the association work against the number of detections, with its 2 ms budget. Drag the crowd up, then switch on the cap.

120

Illustrative cost model: 20 ns per track-detection pair test, as many tracks as kept detections, a 2 ms association budget. The scene is seeded.

The cost, worked

work = c × n2     bounded: work ≤ c × K2
work
the time of the all-pairs comparison in one cycle
c
the cost of one pair test, here an illustrative 20 ns
n
the number of detections (and tracks) this cycle: set by the world
K
the cap: the most the step will ever see. Set by you

n = 64: 64² = 4,096 tests × 20 ns = 82 µs  ·  n = 400: 400² = 160,000 × 20 ns = 3.2 ms

The capped version can never exceed 82 µs, whatever the car park holds. That single line is a promise you can write in a design document and test.

Four habits of bounded code

  1. Fixed capacities everywhere. Every container has a compile-time maximum: tracks, detections, candidate pairs. Chapter 3 gave the tools.
  2. A static bound on every loop. A loop runs over a fixed-capacity container, or has an explicit counter limit. Safety coding standards ask for this so a reviewer can see the maximum.
  3. Cap iterative solvers. A Newton or optimisation loop stops after, say, 10 iterations even if it has not converged, and reports "not converged" instead of spinning.
  4. Cap the input at the door. Decide what the expensive step may see, and cut the input down before it gets there.

What to drop, and how to say so

Capping means dropping, and dropping is a safety decision. Choose the rule with the people who own the downstream function. Common rules keep the detections nearest the vehicle, the ones in the vehicle's path, or the ones with the highest confidence. Whatever you choose, follow two rules.

#include <algorithm>
#include <array>
#include <cstdint>

struct Detection { float range_m; float conf; std::uint16_t idx; };  // idx: position in the input

constexpr int kMaxIn = 512;                // the most the sensor driver can ever deliver
constexpr int kKeep  = 64;                 // the most the association step may see

struct Overflow { int offered = 0, kept = 0, dropped = 0; float nearest_dropped_m = 0; };

// Keeps the kKeep nearest detections. The work is bounded by kMaxIn, never by the scene.
// Ties break on idx, so the same input always keeps the same detections.
int keepNearest(const Detection* in, int n, std::array<Detection, kKeep>& out, Overflow& ov) {
  static std::array<Detection, kMaxIn> scratch;   // reserved once, one caller thread only
  n = std::min(n, kMaxIn);                 // a driver bug cannot make us loop longer
  std::copy(in, in + n, scratch.begin());
  const int keep = std::min(n, kKeep);
  auto nearer = [](const Detection& a, const Detection& b) {
    return a.range_m != b.range_m ? a.range_m < b.range_m : a.idx < b.idx;
  };
  // partial_sort: about n * log(keep) comparisons, a bound we can state in review
  std::partial_sort(scratch.begin(), scratch.begin() + keep, scratch.begin() + n, nearer);
  std::copy(scratch.begin(), scratch.begin() + keep, out.begin());
  ov.offered = n; ov.kept = keep; ov.dropped = n - keep;
  ov.nearest_dropped_m = ov.dropped ? std::min_element(scratch.begin() + keep,
                             scratch.begin() + n, nearer)->range_m : 0.0f;
  return keep;                             // the caller publishes ov every cycle
}

Why partial_sort and not a full sort? The standard states its cost: about n × log K comparisons. For n = 512 and K = 64 that is about 512 × 6 = 3,072 comparisons, a bound you can put in a budget. A full sort would do more work than needed.

Failure: the overflow nobody saw

A capped tracker passes every test. In a busy city a pedestrian close to the car is missed. The cap kept the 64 highest-confidence detections, and the pedestrian was partly hidden, so its confidence was low. Diagnose it from the overflow report: how often the cap was hit, and the range of the nearest dropped detection. Fix the rule (nearest first, or a reserved quota for the vehicle's path) and add the scene to the regression set.

An interviewer asks: "Your association step is O(n²). How do you make its time bounded, and what must you add so it stays safe?"

Chapter 6

Threads without waiting

See how a lock lets a slow thread stall a fast one, and pass data between threads without any lock at all

Three people share one bathroom key. The night nurse has the highest priority, the cook is in the middle, and the cleaner is lowest. The cleaner takes the key. The nurse needs it, so she waits. Then the cook arrives with a long job that outranks the cleaner, and the cleaner stops to help him. The nurse, who outranks everyone, now waits for the cook's whole job.

That is priority inversion: a high-priority task waits for a low-priority task that holds a shared resource, while a medium-priority task, unrelated to both, keeps the low one from finishing. The high-priority task's delay has no bound, because it depends on how long the medium task runs.

In software, the key is a mutex (a lock): only one thread may hold it, and others that want it wait. The code that runs while holding it is the critical section. A real-time scheduler runs the highest-priority ready thread, so the story above can happen on any real-time system with locks.

Invert the priorities

High is the brake controller, Medium a log compressor, Low a diagnostics task that holds the shared lock for 2 ms. Play the timeline. Then switch on priority inheritance, or change how long Medium runs.

8.0 ms

Toy schedule on one core, 0.1 ms steps, strict priorities. High is released at 2.0 ms with a 10 ms deadline and needs 2 ms of work, all under the lock. Low takes the lock at 1.0 ms. Medium is released at 2.5 ms.

The cost, worked

RH = CH + BH
RH
High's response time: from its release to its finish
CH
High's own execution time: 2 ms here
BH
blocking: the time High is ready but waits for a lower-priority task

no inheritance: B = 0.5 (Low) + 8 (Medium) + 0.5 (Low) = 9 ms, R = 2 + 9 = 11 ms > 10 ms

with inheritance: B = 1 ms (rest of Low's critical section), R = 2 + 1 = 3 ms

Priority inheritance fixes the story. While Low holds a lock that High wants, Low runs at High's priority. Medium can no longer push it aside, so Low finishes its critical section and releases the lock. High's blocking is now bounded by the longest critical section of a lower-priority task. A related scheme, the priority ceiling, raises any holder to a fixed ceiling priority as soon as it takes the lock.

This is not a classroom problem. In 1997 the Mars Pathfinder lander kept resetting itself on Mars. The cause was priority inversion around a mutex that guarded shared data. Engineers fixed it by enabling priority inheritance on that mutex, through a software update sent from Earth.

#include <pthread.h>

// A mutex with priority inheritance (POSIX). While a low-priority thread holds it
// and a high-priority thread waits, the holder runs at the waiter's priority,
// so medium-priority work cannot keep it off the CPU.
class PiMutex {
 public:
  PiMutex() {
    pthread_mutexattr_t a;
    pthread_mutexattr_init(&a);
    pi_ = pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT) == 0;  // not every OS has it
    init_ = pthread_mutex_init(&m_, &a) == 0;
    pthread_mutexattr_destroy(&a);
  }
  ~PiMutex() { if (init_) pthread_mutex_destroy(&m_); }
  PiMutex(const PiMutex&) = delete;
  PiMutex& operator=(const PiMutex&) = delete;

  bool ok() const { return pi_ && init_; }  // refuse to start the system if this is false
  void lock() { pthread_mutex_lock(&m_); }
  void unlock() { pthread_mutex_unlock(&m_); }

 private:
  pthread_mutex_t m_;
  bool pi_ = false, init_ = false;
};

// Usage: keep the critical section short and bounded, even with inheritance.
//   std::lock_guard<PiMutex> g(stats_mutex);   // PiMutex meets the Lockable shape
//   stats.copyFrom(latest);                     // a fixed-size copy, no allocation

Better still: do not wait at all

Inheritance bounds the wait. Removing the wait is better. Most data in a perception stack flows one way: a sensor thread produces frames, a tracker thread consumes them. For one producer and one consumer, a single-producer single-consumer ring buffer (SPSC) passes data with no lock.

The ring is an array of N slots and two counters. The producer owns tail: the count of items ever written. The consumer owns head: the count of items ever read. Each counter has exactly one writer, so the two threads never fight over a variable. The ring is empty when head equals tail, and full when tail minus head equals N.

One question remains: when the consumer sees tail move, is the data in the slot really there yet? Compilers and processors may reorder memory operations to go faster. Without care, the consumer could see the new tail before the data it announces. Two memory orders on std::atomic close that gap.

Memory orderWhat it promisesUse in the ring
relaxedthe operation itself is atomic; no ordering with other memoryreading your own counter
release (store)earlier writes become visible no later than this storepublishing tail after the data, head after the read
acquire (load)if you see a release store's value, you see everything before itreading the other thread's counter
seq_cst (the default)acquire and release, plus one total order of all such operationssafe but stronger than SPSC needs; can cost more on some processors

So the producer writes the data, then stores tail with release. The consumer loads tail with acquire, then reads the data. The pair forms a handshake: "data first, then the flag" on one side, "flag first, then the data" on the other.

Step the ring

Each button runs one small step of that thread, in the order the code runs it. Interleave them any way you like. Then switch on the bug: the producer's tail becomes visible before its data, as can happen with relaxed ordering.

An 8-slot ring. Each push and pop is split into the steps of the code below. The bug mode shows the visible order that release forbids; on real hardware it appears rarely and only under load, which is why such bugs survive testing.

#include <atomic>
#include <cstddef>
#include <type_traits>

// One producer thread, one consumer thread, no locks. N slots, N a power of two.
// head_ and tail_ count forever; slot = count & (N - 1). Unsigned wrap-around
// keeps tail_ - head_ correct even after the counters overflow.
template <typename T, std::size_t N>
class SpscRing {
  static_assert(N >= 2 && (N & (N - 1)) == 0, "N must be a power of two");
  static_assert(std::is_trivially_copyable_v<T>, "copy plain data, never own memory");

 public:
  bool push(const T& v) {                                      // producer thread only
    const std::size_t t = tail_.load(std::memory_order_relaxed);  // only we write tail_
    const std::size_t h = head_.load(std::memory_order_acquire);  // see the consumer's reads finish
    if (t - h == N) return false;                              // full: drop and count, never wait
    buf_[t & (N - 1)] = v;                                     // 1. write the data
    tail_.store(t + 1, std::memory_order_release);             // 2. then publish it
    return true;
  }

  bool pop(T& out) {                                           // consumer thread only
    const std::size_t h = head_.load(std::memory_order_relaxed);  // only we write head_
    const std::size_t t = tail_.load(std::memory_order_acquire);  // pairs with the release above
    if (t == h) return false;                                  // empty
    out = buf_[h & (N - 1)];                                   // 1. read the data
    head_.store(h + 1, std::memory_order_release);             // 2. then free the slot
    return true;
  }

 private:
  alignas(64) std::atomic<std::size_t> head_{0};   // written by the consumer
  alignas(64) std::atomic<std::size_t> tail_{0};   // written by the producer: another line,
  alignas(64) T buf_[N] = {};                      // so the two threads do not false-share
};

Walk through the four memory orders once more. The producer reads its own tail relaxed, because no other thread writes it. It reads head with acquire, so it sees that the consumer finished reading a slot before it overwrites it. It writes the slot, then publishes tail with release. The consumer mirrors this. The alignas(64) on each counter keeps head and tail on separate cache lines, so the two threads do not false-share (Chapter 4).

Both calls finish in a fixed number of steps whatever the other thread does. That property is called wait-free. When the ring is full, push returns false at once. The producer counts the drop and moves on. It never waits for the consumer.

Failure: a test that passes a million times

A home-made queue passes every unit test, then corrupts one message a day on the vehicle. Ordering bugs hide on fast desktop processors and appear on other hardware or under load. Diagnose it with ThreadSanitizer, which reports data races in a test build. Add a stress test that runs both threads flat out for hours and checks a sequence number in every message. Better still, keep one reviewed SPSC ring in the codebase and use only that one.

An interviewer asks: "In an SPSC ring, why must the producer store tail with release, after writing the slot?"

Chapter 7

Same input, same output

Remove every hidden input from a cycle, so a recorded drive replays exactly

A test driver reports that the car braked for nothing at a junction. You have the recording: every sensor frame, timestamped. You replay it through the software on your desk. No brake. You replay it again. This time, a brake. The bug is real, but you cannot catch it, because the software does not give the same answer twice.

Software is deterministic when the same inputs always give the same outputs, bit for bit. You need it for three jobs. You reproduce a field failure from a recording. You run regression tests that compare outputs exactly. And you show a safety reviewer that the software you tested is the software that runs.

Nondeterminism always comes from a hidden input: something the code reads that is not in the recording. Find the hidden inputs and you find the cure.

Run it twice and diff

The same recording goes through the same tracker twice. Each switch adds one hidden input. Press Run twice and read the diff: red lines differ.

Toy tracker output: eight tracks with id, position and state. Each switch perturbs the second run the way that hidden input would. The final line is an FNV-1a hash of the fields, as in the code below.

The five hidden inputs

  1. Uninitialised memory. A field never set holds whatever was there before. Reading it is undefined behaviour, and its value differs between runs. Initialise every member, and hash fields, not raw structs, because padding bytes between fields are not set either.
  2. Hash-container order. std::unordered_map iterates in an order that depends on the hash, the bucket count and the insertion history. Hash pointers and the order also depends on memory addresses, which change between runs. Iterate in a defined order: by index, or over a sorted array.
  3. Floating-point order. Floating-point addition is not associative, so a different order of the same additions can change the last bits. Options such as fast-math let the compiler reorder; a fused multiply-add rounds once instead of twice; a parallel sum split differently across threads adds in a different order.
  4. Thread timing. If two threads race to deliver a radar and a camera frame, the order the tracker sees them can change between runs. Make the order a function of timestamps, not of arrival.
  5. Time and randomness. A call to the wall clock or to a random source inside the cycle is an input that the recording does not hold. Pass time in from the sensor timestamps, and log every seed.

Why order changes a float sum

(a + b) + c ≠ a + (b + c)    in floating point
a
here 100,000,000 (108) as a 32-bit float
b
here 1
c
here −100,000,000

A 32-bit float has 24 bits of precision. Near 108, consecutive floats are 8 apart, so 108 + 1 rounds back to 108.

(108 + 1) − 108 = 108 − 108 = 0  ·  (108 − 108) + 1 = 0 + 1 = 1

The third grouping, 108 + (1 − 108), also gives 0, because 1 − 108 rounds to −108. Three groupings of the same three numbers, two different answers. In a tracker, such a last-bit difference can flip a gate test, which changes an association, which changes a track id. Small differences grow.

Making a run replayable

The cure has four parts. Feed every hidden input in explicitly. Log those inputs with the recording. Hash the outputs every cycle. And in CI, replay a recording twice and compare the hashes.

#include <cstdint>
#include <cstring>
#include <random>

struct TrackOut { std::uint32_t id; float x, y; std::uint8_t state; };  // 3 bytes of padding

// Hash the FIELDS, never the raw struct: its padding bytes are not set by
// field-by-field writes, and they can differ between two identical runs.
struct Fnv1a {
  std::uint64_t h = 1469598103934665603ull;
  void bytes(const void* p, std::size_t n) {
    const auto* b = static_cast<const unsigned char*>(p);
    for (std::size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; }
  }
  void u32(std::uint32_t v) { bytes(&v, sizeof v); }
  void f32(float v) { std::uint32_t u; std::memcpy(&u, &v, sizeof u); u32(u); }  // exact bits
};

std::uint64_t hashOutputs(const TrackOut* t, int n) {
  Fnv1a f;
  for (int i = 0; i < n; ++i) { f.u32(t[i].id); f.f32(t[i].x); f.f32(t[i].y); f.u32(t[i].state); }
  return f.h;
}

// Everything a run may not invent for itself comes in through this struct:
// the time, and the random seed. A replay passes the logged values back in.
struct RunInputs {
  std::uint64_t frame_time_ns;   // from the sensor timestamp, never from the wall clock
  std::uint32_t seed;            // logged with the run
};

float jitterForTest(const RunInputs& in) {
  std::mt19937 rng(in.seed);     // the mt19937 sequence is fixed by the C++ standard...
  return static_cast<float>(rng() % 1000) / 1000.0f;  // ...but std::normal_distribution
}                                // and friends may differ between library versions

Notice the comment on the random generator. The C++ standard fixes the exact sequence of std::mt19937 for a given seed. It does not fix the algorithms of distributions such as std::normal_distribution, so two standard libraries can turn the same sequence into different numbers. For replay across platforms, write your own small distribution code.

A note on floats across machines. Bit-exact results on one build and one processor are achievable with the habits above. Bit-exact results across different compilers, processors or math libraries are much harder: functions such as sin and exp may differ in the last bit. Many teams compare across platforms with a small tolerance, and require exact equality only within one build.

Failure: the replay that drifts after 40 seconds

Two replays match for 40 seconds, then a track id differs and everything after diverges. Diagnose it by hashing outputs every cycle and finding the first cycle where the hashes differ. Then hash each stage's output in that cycle to find the first stage that differs. The usual culprits are an iteration over an unordered container or a tie in a sort without a tie-break.

An interviewer asks: "Two replays of the same log give different track ids after a few seconds. Where do you look first?"

Chapter 8

Errors without surprises

Report a failure in fixed time, and turn it into a mode the system can act on, never a crash

Mud splashes onto the radar. For a second it reports nonsense: a range of "not a number", then a frame that is 200 ms old. The software must notice, say so, and keep driving on the camera. What it must not do is stop.

C++ offers several ways to report an error, and they differ in one way that matters here: how long the report takes, and whether that time is bounded.

Fail without falling over

Three seconds of radar frames at 100 Hz, with faults injected at fixed times. Pick a policy and read the strip of cycle times and the mode lane below it.

Toy costs: a normal cycle takes about 4 ms; the throw path adds 0.5 to 3 ms (illustrative: real cost varies widely by platform and stack depth); a restart after abort takes 300 ms of no output. Debounce: degrade after 3 bad frames in a row, recover after 10 good ones.

Exceptions on the hot path

Most C++ compilers implement exceptions so that the normal path costs almost nothing. The cost moves to the throw: the runtime searches tables to unwind the stack and runs destructors on the way. That path is slow compared with a return, and its time depends on how deep the stack is. In common implementations it also allocates the exception object on the heap, which Chapter 3 banned.

So many real-time teams compile with exceptions off (-fno-exceptions on GCC and Clang) and use return values for errors. Some coding standards for safety-critical C++ forbid exceptions; others allow them under strict rules. Either way, a hot path should not throw.

Error codes that cannot be ignored

The alternative is to return the error as a value. C++23 adds std::expected for this. In C++17, a small struct does the same job. Mark it [[nodiscard]] and the compiler warns when a caller drops the result.

#include <cmath>
#include <cstdint>

enum class Err : std::uint8_t { Ok, Stale, NotFinite, OutOfRange, QueueFull };

// A small expected-style result (C++23 has std::expected; this works in C++17).
// The error is part of the return type, so the caller cannot forget it exists.
template <typename T>
struct [[nodiscard]] Result {
  T   value{};
  Err err = Err::Ok;
  bool ok() const { return err == Err::Ok; }
};

struct RadarFrame { std::uint64_t stamp_ns; float range_m, range_rate_mps; };

// Checks a frame in fixed, bounded time. No throw, no allocation, no logging I/O here.
Result<RadarFrame> validate(const RadarFrame& f, std::uint64_t now_ns) {
  constexpr std::uint64_t kMaxAgeNs = 50'000'000;          // 50 ms: illustrative
  if (now_ns < f.stamp_ns || now_ns - f.stamp_ns > kMaxAgeNs) return {f, Err::Stale};
  if (!std::isfinite(f.range_m) || !std::isfinite(f.range_rate_mps)) return {f, Err::NotFinite};
  if (f.range_m < 0.0f || f.range_m > 250.0f) return {f, Err::OutOfRange};
  return {f, Err::Ok};
}

// The caller turns errors into a mode, not a crash. Debounce: one bad frame is a
// glitch; three in a row is a fault that the safety layer must hear about.
struct RadarHealth {
  int bad_in_row = 0;
  bool degraded() const { return bad_in_row >= 3; }
  void update(Err e) { bad_in_row = (e == Err::Ok) ? 0 : bad_in_row + 1; }
};

The validator runs in fixed time: a few compares, no loop, no allocation, no logging I/O. It records what was wrong in a small enum. A separate, slower thread can format the log message later.

From an error to a mode

One bad frame is often noise. Several in a row is a fault. Debouncing waits for k bad frames in a row before declaring a fault. How big should k be?

Pfalse = pk      tdetect = k × T
Pfalse
the chance per frame that independent glitches alone trip the fault
p
the chance that one frame is a harmless glitch
k
bad frames in a row needed to declare the fault
tdetect
the delay before a real, lasting fault is declared
T
the frame period

p = 0.01, k = 3: P = 10−6 per frame  ·  at 100 Hz: 10−6 × 360,000 = 0.36 false faults per hour  ·  tdetect = 3 × 10 ms = 30 ms

Raise k to 4 and false faults drop a hundredfold, to one in about 280 hours, at the price of 10 ms more delay. That trade is a safety decision, so it belongs in the design document with both numbers. The independence assumption is the weak point: glitches often come in bursts, so measure p and its bursts from logs.

Asserts, checks and what to do in flight

Failure: the error that stalled the cycle

Cycle times spike only when a sensor misbehaves. Diagnose it by lining up the spikes with error counts. The usual cause is error handling that does slow work in the cycle: building a log string, writing a file, or throwing. Move formatting and I/O to a low-priority thread fed by an SPSC ring of small error records.

An interviewer asks: "Your radar driver can return NaN. How should the hot path handle it?"

Chapter 9

Proving it stays fast

Turn every rule of this lesson into a check that runs on every change and fails the build when the tail grows

Six months after launch, a new engineer adds a std::map lookup inside the tracking loop. It is correct, it is reviewed, and it ships. The average cycle time moves by 0.1 ms. Nobody notices for two releases, until the tail reaches the deadline on a busy road.

Real-time behaviour is not a property you build once. Every change can break it. So the habits of this lesson must become automated checks that run on every change. They run in continuous integration (CI): the build server that compiles and tests each change before it merges.

Gate the regression

Eight commits, each measured on the worst-case scenes. Two of them hurt the tail. Choose what the gate checks and how many cycles it measures, and see which commits it blocks.

Toy measurements from seeded distributions. Commit 4 adds a map lookup that slows 3% of cycles by 2 to 4 ms; commit 6 adds logging through a mutex that stalls about 1 cycle in 1,000 by 8 to 20 ms; commit 8 removes the map lookup.

How many cycles must you measure?

A gate on p99.9 is useless if the test never runs long enough to see a p99.9 event. Ask: how many cycles n do I need so that at least one sample lands beyond the q-quantile, with high confidence?

n ≥ ln α / ln q
n
the number of independent cycles to measure
α
the chance you accept of seeing no sample beyond the quantile, for example 0.05
q
the quantile you care about: 0.99 for p99, 0.999 for p99.9

It comes from one line: each cycle stays below the q-quantile with probability q, so all n stay below with probability qn. Set qn ≤ α and take logs.

p99: ln 0.05 / ln 0.99 = −2.996 / −0.01005 = 299 cycles  ·  p99.9: −2.996 / −0.0010005 = 2,995 cycles

That is the bare minimum to see the tail once. To estimate it well you want ten times more. At 100 Hz, 30,000 cycles is five minutes of replay per scene. Real cycles are not independent either: a crowd lasts many cycles. So replay many different hard scenes, not one scene many times.

The CI budget test

The test replays the worst recorded scenes, times every cycle, and fails the build when p99 or the maximum crosses its budget. It runs on the target hardware, or on a machine whose timing you have related to the target. A desktop that is three times faster hides regressions.

#include <algorithm>
#include <cstdio>
#include <vector>

// A CI test: replay the worst scenes, time every cycle, fail the build if
// the tail breaks its budget. The vector is fine here: this runs on a
// build machine, not on the vehicle, and is reserved before timing starts.
struct Budget { double p99_ms, max_ms; };

int checkBudget(std::vector<double>& cycle_ms, Budget b) {
  if (cycle_ms.size() < 3000) {            // too few samples to say anything about p99.9
    std::printf("FAIL: only %zu cycles measured\n", cycle_ms.size());
    return 2;
  }
  std::sort(cycle_ms.begin(), cycle_ms.end());
  const std::size_t i99 = (cycle_ms.size() * 99) / 100;    // nearest-rank style index
  const double p99 = cycle_ms[std::min(i99, cycle_ms.size() - 1)];
  const double mx = cycle_ms.back();
  std::printf("p99 %.2f ms (budget %.2f), max %.2f ms (budget %.2f)\n",
              p99, b.p99_ms, mx, b.max_ms);
  if (p99 > b.p99_ms || mx > b.max_ms) {
    std::printf("FAIL: tail latency over budget\n");
    return 1;                              // a nonzero exit code fails the CI job
  }
  return 0;
}

A tripwire for allocations

Timing tests catch what is slow today. Rule checks catch what will be slow tomorrow. The strongest is an allocation tripwire: in test builds, replace the global operator new and count every call made during a cycle. The test then demands zero.

#include <atomic>
#include <cstdlib>
#include <new>

// Test builds only: replace global operator new so that any heap allocation
// made while a cycle runs is counted. A unit test then asserts the count is 0.
thread_local bool t_in_cycle = false;      // true only inside runCycle()
std::atomic<long> g_cycle_allocs{0};

void* operator new(std::size_t n) {
  if (t_in_cycle) g_cycle_allocs.fetch_add(1, std::memory_order_relaxed);
  if (void* p = std::malloc(n ? n : 1)) return p;
  throw std::bad_alloc();                  // the standard contract for operator new
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

struct CycleScope {                        // RAII: marks the hot path
  CycleScope() { t_in_cycle = true; }
  ~CycleScope() { t_in_cycle = false; }
};

// In the test:
//   { CycleScope s; runCycle(worstScene); }
//   EXPECT_EQ(g_cycle_allocs.load(), 0);   // one push_back that grows will fail this

The rest of the safety net

Failure: the flaky gate

The timing gate fails one build in five for no code change, so engineers learn to press "retry". Diagnose it by running the same build twenty times and plotting the spread of p99 and max. Usual causes: too few cycles (see the equation), a shared CI machine with noisy neighbours, or frequency scaling that changes the clock speed. Fix the machine (dedicated cores, fixed clock), measure more cycles, and gate on a margin above the measured noise.

An interviewer asks: "How would you stop tail-latency regressions from reaching the vehicle?"

Chapter 10

The cycle bench

Build a perception cycle stage by stage, load the scene, inject hazards, and find what breaks it

Here is a whole perception cycle on one bench. Five stages run in order every 10 ms: take in the sensor frame, associate detections with tracks, update the tracks, run the monitors, publish the result. For each stage you choose an implementation: the real-time one from this lesson, or the one a busy engineer might write first.

Load the scene, switch on hazards, and read the distribution of 3,000 cycles. Try to keep zero missed deadlines with the scene at 200 objects and every hazard on. Then make one bad choice at a time and see which hazard it exposes.

Run the cycle bench

Top: the last 600 cycles against the deadline. Middle: the histogram of all 3,000, with mean, p99 and max. Bottom: the slowest cycle, split by stage.

Ingest
Associate
Track store
Monitor
Publish
120

Toy timing model with illustrative costs: about 1.9 ms to take in and preprocess a frame, 20 ns per association pair, 20 µs per track update (twice that and noisier for a heap list), occasional allocator stalls of 4 to 20 ms, logger stalls of 2 to 15 ms, crowds that triple the scene for one second in every five. A real bench measures your code on your target.

What to look for

The bottom bar is the habit to keep. When a cycle is slow, do not guess. Ask which stage took the time. The code below gives every stage its own timer, in a fixed array, so the slowest cycle can explain itself.

#include <array>
#include <chrono>
#include <cstdint>

enum Stage : int { kIngest, kAssociate, kUpdate, kMonitor, kPublish, kStageCount };

// Per-cycle stage times, in a fixed array that a monitor thread can copy out.
struct CycleTimes { std::array<std::uint32_t, kStageCount> us{}; };

// RAII stage timer: the destructor records the time even on an early return.
class StageTimer {
 public:
  using Clock = std::chrono::steady_clock;
  StageTimer(CycleTimes& out, Stage s) : out_(out), s_(s), t0_(Clock::now()) {}
  ~StageTimer() {
    const auto d = std::chrono::duration_cast<std::chrono::microseconds>(Clock::now() - t0_);
    out_.us[s_] = static_cast<std::uint32_t>(d.count());
  }
  StageTimer(const StageTimer&) = delete;
  StageTimer& operator=(const StageTimer&) = delete;

 private:
  CycleTimes& out_;
  Stage s_;
  Clock::time_point t0_;
};

// One cycle. Each block is a scope, so each timer stops exactly where its stage ends.
void runCycle(CycleTimes& ct) {
  { StageTimer t(ct, kIngest);    /* copy the frame into a pool slot        */ }
  { StageTimer t(ct, kAssociate); /* gate, then assign, on capped input      */ }
  { StageTimer t(ct, kUpdate);    /* Kalman updates over SoA arrays          */ }
  { StageTimer t(ct, kMonitor);   /* plausibility checks, error codes        */ }
  { StageTimer t(ct, kPublish);   /* push to the SPSC ring; drop if full     */ }
}

The timer is an RAII object (resource acquisition is initialisation): it starts in its constructor and records in its destructor. So the time is recorded however the stage exits, including an early return on an error code.

The worked budget behind the defaults

at 120 objects, all real-time choices, no hazards ingest 0.40 ms copy + 1.50 ms preprocess = 1.90 ms associate 0.30 + 64² × 20 ns = 0.38 ms update 64 × 20 µs = 1.28 ms monitor 0.50 ms publish 0.10 ms cycle about 4.2 ms of a 10 ms period every pair at 360 objects (a crowd): 0.30 + 360² × 20 ns = 2.9 ms, update 7.2 ms

Failure: the bench passes, the vehicle fails

The bench says zero misses; the vehicle logs show some. Diagnose it by comparing the bench's inputs and machine with the vehicle's: scene density, other processes on the same processor, clock speed, and temperature throttling. Then feed the vehicle's own field histograms back into the bench as new worst-case scenes.

An interviewer asks: "Cycle-time spikes appear every few seconds in blocks, and the mean is fine. The scene is a busy junction. What is the most likely cause?"

Chapter 11

Interview arsenal

Gather the numbers, the design frames, the drills and the debugging stories in one place

Here is the lesson in one paragraph. A real-time cycle is judged by its worst case, so the mean is the wrong number; report p99.9 and the max, measured on the target. Time goes to computation, memory and waiting. Remove the surprises from each: allocate at start-up only, lay data out for the cache, cap every input and loop, and pass data between threads without locks.

Make every run replayable by removing hidden inputs. Report errors as values in fixed time and turn them into modes, never crashes. Then turn each rule into a check in CI, so it stays true after the next hundred changes.

From symptom to cause

Pick a symptom from a field report. The cards light up the causes to check first, in order, and the read-out says what to log.

A study aid: real incidents can have several causes at once. Always confirm with per-stage timing and a replay.

Cheat sheet

IdeaOne lineNumber to remember
Misses per hourp × f × 36000.1% at 100 Hz: 360 an hour
Mean hides the tail990 at 4 ms, 10 at 25 msmean 4.21 ms, max 25 ms
Response timeR = J + C ≤ D; U = C / TT 20, C 15, J 6: R 21 > 20
Budget slackperiod minus the sum of stage budgets33.3 − 29.0 = 4.3 ms (13%)
Percentilesrank ⌈q n⌉ in sorted orderp99 ignores 1 cycle a second at 100 Hz
Memory costhit vs misson the order of 1 ns vs 100 ns
Vector growthdoubling from empty to 1,00011 allocations; worst push copies 512
FragmentationF = 1 − largest free / total free1 − 5/19 = 0.74
AoS vs SoAlines ≈ ∑ ⌈n s / 64⌉512 tracks: 512 lines vs 64
Bounded workc × K² with a cap K64² × 20 ns = 82 µs; 400² = 3.2 ms
Priority inversionRH = CH + BH11 ms without inheritance, 3 ms with
SPSC ringwrite, then release tail; acquire tail, then readfull when tail − head = N
Float order(a + b) + c ≠ a + (b + c)(108 + 1) − 108 = 0 in float
DebounceP = pk, delay k Tp 0.01, k 3: 0.36 an hour, 30 ms
Samples for a quantilen ≥ ln α / ln qp99.9 at 95%: 2,995 cycles

Three system design prompts

1. Design the threading and memory plan for an onboard tracker

Camera at 30 Hz and radar at 20 Hz (illustrative) feed a tracker whose output goes to emergency braking. It shares a processor with logging and diagnostics.

  1. Clarify: deadlines (hard for the braking output, soft for display), maximum objects, sensor latencies, the processor and its other tenants.
  2. Threads: one high-priority thread for the tracker on a dedicated core; sensor threads produce into SPSC rings; logging runs low-priority and is fed by its own ring. No locks on the hard path; any unavoidable lock uses priority inheritance and a short, bounded critical section.
  3. Memory: all pools, arenas and fixed containers sized for the worst case at start-up; pages touched and locked; an allocation tripwire in CI.
  4. Time: order fusion by sensor timestamp, not arrival; a latency budget per stage with 10% or more slack; per-stage timers and a histogram in the product.
  5. Failure: capacity overflows are reported; sensor faults become degraded modes; a missed deadline is counted and reported to the safety layer.
  6. Proof: worst-case scene replay in CI with p99 and max budgets, deterministic replay checks, sanitizers, soak tests.

2. A learned model's runtime varies from 8 to 30 ms. Make the pipeline real-time

  1. Separate the paths: the model runs on its own thread or accelerator; the deterministic layer never waits on it.
  2. Hand-off: the model publishes into an SPSC ring with a timestamp; the tracker takes the newest result each cycle and knows its age.
  3. Bound the age: if the newest result is older than a limit, the tracker predicts forward, flags reduced confidence, and leans on other sensors.
  4. Budget honestly: measure the model's tail on the target and size the downstream design for it, not for its mean.

3. Write the engineering standard for a new real-time C++ team

  1. Rules: no heap after start-up; fixed capacities; a static bound on every loop; no exceptions or RTTI on the hot path; no blocking calls on hard threads; initialise everything; no unordered iteration where order matters.
  2. Base: adopt a published rule set (MISRA C++ or the AUTOSAR C++14 guidelines) with a written list of deviations.
  3. Tooling: warnings as errors, static analysis, sanitizers, an allocation tripwire, deterministic replay, timing gates.
  4. Review: a short checklist for every change to the hot path: what allocates, what can block, what is the loop bound, what is the worst case.
  5. Culture: report p99.9 and max, never the mean alone; every overflow and degraded mode has an owner.

Three coding drills

  1. Fixed vector. Write FixedVector<T, Cap> with push_back that returns false when full, correct alignment, and destructors run in clear(). Test it with std::string under AddressSanitizer.
  2. SPSC ring. Write the ring from Chapter 6 from memory, with the four memory orders. Explain each one aloud. Test it with two threads, a sequence number in every message, and ThreadSanitizer.
  3. Latency histogram. Write a fixed-bucket histogram with an overflow bucket, a true max and a percentile query. Test p99 and p99.9 on the 990 + 10 example.

Here is one answer to the first drill. The points an interviewer looks for are alignment, placement new, explicit destructor calls, and the "full" result instead of growth.

#include <cstddef>
#include <new>
#include <utility>

// Drill answer: a vector with a fixed capacity and no heap. push_back reports
// "full" instead of reallocating, so its cost never changes.
template <typename T, std::size_t Cap>
class FixedVector {
 public:
  FixedVector() = default;
  FixedVector(const FixedVector&) = delete;            // keep the drill small
  FixedVector& operator=(const FixedVector&) = delete;
  ~FixedVector() { clear(); }

  bool push_back(const T& v) {
    if (n_ == Cap) return false;                       // full: the caller must decide
    ::new (static_cast<void*>(raw(n_))) T(v);
    ++n_;
    return true;
  }
  void pop_back() { if (n_) { --n_; ptr(n_)->~T(); } }  // empty pop is a no-op, not UB
  void clear() { while (n_) pop_back(); }               // destroy in reverse order

  T& operator[](std::size_t i) { return *ptr(i); }      // unchecked, like std::vector
  std::size_t size() const { return n_; }
  static constexpr std::size_t capacity() { return Cap; }

 private:
  unsigned char* raw(std::size_t i) { return buf_ + i * sizeof(T); }
  T* ptr(std::size_t i) { return std::launder(reinterpret_cast<T*>(raw(i))); }
  alignas(T) unsigned char buf_[Cap * sizeof(T)];
  std::size_t n_ = 0;
};

Three debugging scenarios

  1. "A 30 ms spike every few minutes, getting more frequent over the day." Suspect the heap: a container that grows in rare scenes, plus fragmentation. Check: the allocation tripwire on a replay of the day; memory use over time. Fix: reserve or make fixed-capacity; pre-touch and lock memory.
  2. "The brake controller misses deadlines only when the log is being uploaded." Suspect priority inversion or a shared lock. Check: scheduler trace for the brake thread's blocked time and who held the lock. Fix: an SPSC ring to the logger; priority inheritance on any remaining lock.
  3. "Bit-exact replays pass on x86 CI but differ on the vehicle's ARM processor." Suspect floating point: fused multiply-add on one target, different math library functions, or different compiler flags. Check: hash per stage to find the first divergence. Fix: the same flags on both, no fast-math, compare across platforms with a tolerance, and keep bit-exact checks per target.

The deterministic layer and the learned model

Deterministic C++ layer (this lesson)Learned model runtime
Worst-case timebounded by design and tested at every capoften input-dependent, measured, harder to bound
Memoryfixed at start-uplarge, usually pre-planned by the runtime
Same input, same outputrequired, checked by replaypossible, but parallel kernels can change the order of sums
Errorserror codes and modes, fixed-time checkswrong outputs that look confident; needs monitors
Reviewline-by-line, against a coding standardby data, metrics and tests on scenes
Role onboardtracking, fusion, monitors, active safety, displaydetection, segmentation, prediction

Reading list

Keep going on this site

The takeaway. Real-time means on time, every time, so judge code by its tail. Allocate at start-up, lay data out for the cache, cap every input, never let a hard thread wait on a soft one, remove hidden inputs, report errors as values, and make CI prove it on every change.

Now press Present or Teach and explain, from memory, why a loop that averages 4 ms can still miss a 10 ms deadline, and name the four hazards that cause it. Then go back to the following car, switch on one hazard at a time, and say which chapter removes each one.

An interviewer asks: "In one sentence, what makes C++ code real-time?"
Real-Time Deterministic C++
Real-time Linux · Multi-target tracking · Back to Gleams