Robot Real-Time Performance

A robot that speaks, listens and moves runs loops hundreds of times a second on one shared computer. One late cycle is a stutter. Learn to find it, count it and remove it.

See why a loop that is fast on average still fails, and which fixes (scheduling, memory, cache, vector instructions, copies) remove which kind of delay.

Pick a setup, then drag the slider for how busy the rest of the robot is. Watch the red cycles appear and vanish. Then we build, piece by piece, every fix this page toggles.

You need a little C or Python and the idea that a computer runs many programs by taking turns. We build the rest from zero.

Built from primary sources, each linked in the Field Guide: the Linux sched(7) and mlock(2) manual pages, Brendan Gregg’s flame graph pages, Ulrich Drepper’s memory paper, the ROS 2 real-time design article, the kernel PREEMPT_RT documentation and Liu and Layland (1973). The numbers on the devices are illustrative unless a note says otherwise.

Run the same loop three ways

60%

Illustrative model, seeded so it is the same on every visit: a cycle takes about 0.3 ms of work. Competing threads, allocation stalls and page faults add delay with the probabilities this page’s chapters explain. The shape is real; the exact numbers depend on the robot.

Chapter 0

The Robot That Must Not Stutter

Meet the three loops inside a talking, listening, moving robot, and learn to count how much of one computer they need

You say a sentence to a small robot in a busy cafe. Its head turns toward you. Its eyes follow your face. A moment later it answers, in a clear voice, while its hand keeps a gentle gesture going. Nothing about this looks hard. But three separate programs must all keep time at once.

If one of them is late, you notice. A late motion command makes the head jerk. A late audio block makes the voice crackle or repeat a sliver of sound. A late camera frame makes the eyes lag behind your face. The robot did not crash. It simply stuttered, and a stutter is what breaks the feeling that something is alive.

Three loops, three periods

A loop here means a piece of code that runs again and again on a clock. The time between two starts is its period, and the rate is one divided by the period. Think of a drummer in a band. The drummer does not decide when to hit; the tempo decides. The loop is the same: the clock decides, and the code must finish its work before the next beat.

Our robot has three drummers. The motion loop reads joint sensors and sends motor commands 500 times a second, so its period is 2 ms. The audio loop takes one block of microphone samples and sends one block to the speaker every 10 ms, 100 times a second. At 48,000 samples a second, one block is 480 samples. The perception loop handles one camera image 30 times a second, so its period is 33.3 ms.

All three share one small computer, along with a network stack, a logger, the language model client and the operating system itself. That sharing is the whole difficulty. Each loop needs the processor for a short time inside its own period, and the computer has to find room for all of them, every time, with no slack to borrow.

The budget: how much of one core does a loop eat?

Call the time one run of a loop's code takes C, its work time. Call its period T. The share of one processor core it uses is C divided by T, called its utilization. A motion loop that works 0.4 ms every 2 ms uses 0.4 / 2 = 0.20, which is 20% of a core. Add the utilizations of all loops on a core and you get the core's total load.

Is 92% load fine? Not quite. A famous result by Liu and Layland (1973) covers the simplest fixed-priority plan, called rate-monotonic scheduling, where the loop with the shortest period always gets the highest priority. For n loops it guarantees every deadline if total utilization stays under n × (21/n − 1). For one loop that is 100%. For two it is 82.8%. For three it is 3 × (21/3 − 1) = 0.780, so 78.0%. For many loops it falls toward 69.3%.

Read that bound as a promise, not a cliff. Under it, the plan is proven safe. Above it, the plan may still work, but nobody has promised you anything, and a single hiccup can tip it over. Above 100% some loop must lose, always. Try the numbers yourself.

Budget the three loops

Each bar is one core, filled by the loops placed on it. The dashed line is the Liu and Layland guarantee for that many loops. Drag a work time, then try two cores.

0.4 ms
3.0 ms
14 ms

The periods (2, 10 and 33.3 ms) are this lesson’s running robot, and the work times are illustrative. The bound n(21/n − 1) is from Liu and Layland (1973); it assumes rate-monotonic priorities and work that never overruns its estimate.

With the starting numbers, one core carries 92% and sits above the 78.0% guarantee. Move vision to its own core and the picture changes: motion plus audio use 50% of core A, under the 82.8% bound, and vision uses 42% of core B. Splitting the loops is the first and cheapest fix. The rest of this page is about the delays that remain even when the average load looks safe.

Why the average lies

The budget above uses C, a single number. But a real loop does not take the same time every run. Most runs are fast. Once in a while a run is slow, because another thread held the core, or memory was not ready, or the data was not in cache. The deadline cares about the slowest run, not the typical one. Chapter 1 builds that idea and gives it its measurements.

Here is the road. Each chapter takes one source of delay, shows how to see it, and shows the fix.

  1. Deadlines, jitter and the tail: why the slowest cycle decides.
  2. Measure first: clocks, latency probes and counting dropped frames.
  3. Profiling: perf, sampling and flame graphs.
  4. Scheduling and affinity: SCHED_FIFO, priorities and pinned cores.
  5. PREEMPT_RT and locks: priority inversion and how inheritance fixes it.
  6. Memory in the hot loop: malloc, page faults and locked memory.
  7. Cache-aware layout: cache lines, arrays of structs and structs of arrays.
  8. Vector instructions: SIMD lanes and what limits them.
  9. Zero-copy pipelines: moving frames without moving bytes.
  10. Field guide: the numbers, a checklist, the core code and the sources.
Three loops use 20%, 30% and 42% of one core, so 92% in total. The guarantee for three rate-monotonic loops is 78.0%. What does that tell you?

Chapter 1

Deadlines, Jitter and the Tail

See why the slowest cycles, not the average ones, decide whether a robot looks smooth, and learn the words and numbers for them

An engineer measures the robot's motion loop and reports good news: it takes 0.4 ms on average, and the budget is 2 ms. The team relaxes. Two days later, a demo visitor watches the arm shiver about every two seconds. The average was true. It was also useless.

An average squeezes thousands of cycles into one number, and it throws away the one thing a deadline cares about: how bad the worst cycles are. To fix the shiver you must look at the cycles the average hid.

Four words you need

A deadline is the latest time a result is useful. For a periodic loop the deadline is usually the start of the next period. Latency is the time from an event to its response, such as from a microphone sample arriving to the speaker block leaving. Jitter is the variation in when a periodic thread really wakes compared with when it should; the ROS 2 design article defines it this way, and notes that the tool cyclictest measures it. Think of a train that is due every ten minutes. Late by two minutes, then early by one, then late by five: that spread is jitter.

The fourth word is determinism: the same inputs give the same timing, not only the same answer. The ROS 2 article draws a sharp line here. A real-time system is defined by a deterministic schedule and a stated, measured maximum latency, not by low latency alone.

How much a miss hurts decides the kind of real-time you need. In hard real-time, a missed deadline is a system failure, as with an autopilot. In soft real-time, a miss lowers quality but is survivable, as with streaming video. Firm real-time sits between: a late result is thrown away, and the system carries on. A robot's motor loop is nearly hard, since a late command can break a gear. Its audio loop is firm: a late block is dropped and you hear a click. Its vision loop is soft.

The tail, in percentiles

To describe the slow cycles, sort all your measured cycle times from fastest to slowest. The percentile p99 is the time that 99% of cycles beat. The p50 is the middle one, the median. The p99.9 is the time that all but one cycle in a thousand beat. The slowest cycle is the maximum. The slow end of the sorted list is called the tail.

Why does a small slice of cycles matter so much? Do the arithmetic. At 500 Hz the loop runs 500 × 60 = 30,000 times a minute. If 99% of cycles are on time, 1% are late, and 1% of 500 is five late cycles every second. If 99.9% are on time, there are still 30 late cycles a minute, one about every two seconds. That is the shiver.

The tail also compounds across stages. Suppose the sensor read, the filter and the motor write each meet the deadline 99% of the time, and their delays are independent. All three are on time together only 0.99 × 0.99 × 0.99 = 0.970 of the time, so 3% of cycles fail somewhere. The more stages a pipeline has, the more its tail grows.

Here is a histogram of 20,000 cycle times. Most cycles bunch near 0.35 ms. A small group sits between 0.8 and 1.7 ms. A very few reach several milliseconds. Move the deadline and watch what it costs.

Move the deadline across the tail

Each bar counts cycles in a 0.1 ms bin. The height uses a log scale, so rare slow cycles stay visible. Red bars are past your deadline. Drag the deadline left and watch the misses per minute climb.

1.5 ms

Illustrative data, seeded: 97.5% of cycles are lognormal around 0.35 ms, 2.4% fall between 0.8 and 1.7 ms (a competing thread held the core briefly), and 0.1% fall between 1.8 and 5.4 ms. Misses per minute assume a 500 Hz loop, so 30,000 cycles a minute.

Look at the mean marker. It sits near 0.4 ms, far left of everything that hurts. Now drag the deadline to 1 ms: about 2.0% of cycles miss, which is nearly 600 a minute. The mean never changed. Only the question changed, from "how long does a typical cycle take?" to "how long does the worst one take?"

WCET: the number you wish you had

Engineers who need a guarantee want the worst-case execution time, called WCET: the longest your code can ever take. For tiny microcontroller code, you can bound it by analysis. On a shared Linux computer you cannot, because caches, other threads, the kernel and the memory system all add delay you do not control. So in practice you do two things. You measure a long run and report the maximum and the high percentiles, and you remove the causes of the tail one by one, which the next chapters do.

Measure it: cyclictest

The standard test is cyclictest. It starts a high-priority thread that sleeps until an exact time, wakes, and records how late it woke. That lateness is the scheduling latency, and its worst values are the tail you will see in your own loops. Run it for hours while the rest of the robot is busy, not on an idle machine.

shell# one thread, priority 90, locked memory, 1 ms interval, 100,000 loops (about 100 seconds)
sudo cyclictest -m -p 90 -t 1 -i 1000 -l 100000
# output: per thread, the Min, Avg and Max wake-up latency in microseconds

The failure mode, as symptom then measurement then fix. The symptom is a rare glitch, once in seconds or minutes. The measurement is the maximum and the p99.9 of loop time or wake-up latency over a long, busy run. The fix depends on the cause, and the causes have different signatures: wake-up delay points to scheduling (Chapters 4 and 5), slow cycles with a quiet scheduler point to memory (Chapter 6), and uniformly slow cycles point to the code itself (Chapters 3, 7 and 8).

A 1 kHz loop meets its deadline 99.9% of the time. How often does it miss, on average?

Chapter 2

Measure First: Clocks, Latency and Dropped Frames

Put a trustworthy clock on every stage, count what is lost, and see why a bigger queue hides an overload instead of fixing it

The robot's voice crackles. Not always. Sometimes after ten seconds, sometimes after two minutes. A teammate says the network is to blame. Another says the speaker driver. A third rewrites a filter that nobody had timed. Everyone is guessing, because nobody has a number.

The first job in performance work is not fixing. It is counting. Before you change a line, you want three things: a clock you can trust, a stamp on each piece of data that says when it was born, and a counter for everything that gets lost.

A clock that never jumps

Your computer keeps two kinds of time. Wall-clock time is the date and hour on the wall. It is set from the network, so it can jump forward or backward when the system corrects it. A timer built on it can measure a negative duration. Monotonic time only moves forward, at a steady rate, from some arbitrary start. On Linux you ask for it with clock_gettime(CLOCK_MONOTONIC, ...). Use monotonic time for every duration, deadline and sleep in a control loop.

Stamp data when it is born

Latency from microphone to speaker means little if you only know when the data reached your code. By then it has already waited in the driver and the kernel. So stamp each frame as early as possible, ideally with the time the hardware captured it, and carry the stamp along with the data. ROS 2 messages have a header field for exactly this. At any later stage, end-to-end latency is simply now minus stamp. Log it as a histogram, never only as an average, for the reasons of Chapter 1.

Sleep until a time, not for a time

Here is a small bug that costs real rate. A loop does its work, then calls sleep(2 ms). The work takes 0.4 ms. So each turn takes 0.4 + 2.0 = 2.4 ms, and the loop runs at 1 / 2.4 ms = 417 Hz, not 500 Hz. Over one minute it completes 60 / 0.0024 = 25,000 cycles instead of 30,000. The error is not random. It grows every turn, which is called drift. The ROS 2 design article recommends the cure: compute each period's start from a measured time.

The cure is to keep a variable next holding the planned start of the next cycle. Add the period to it every turn, then sleep until that absolute time. A slow cycle now makes the following sleep shorter, so the loop catches up instead of drifting. On Linux this is clock_nanosleep with the flag TIMER_ABSTIME.

cstruct timespec next; clock_gettime(CLOCK_MONOTONIC, &next);
for (;;) {
    do_work();                                   /* about 0.4 ms */
    next.tv_nsec += 2000000;                      /* period: 2 ms */
    if (next.tv_nsec >= 1000000000) { next.tv_nsec -= 1000000000; next.tv_sec++; }
    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);
    /* wake-up lateness = clock_gettime() - next: record it every cycle */
}

Count what you lose

A dropped frame is a piece of data that arrived and was never processed. Cameras, microphones and sensors keep producing at their own pace whether or not your code keeps up. To count drops, give every frame a sequence number and watch for gaps: if frame 41 is followed by frame 44, two were lost. Audio has its own version. An xrun is an underrun (the speaker needed a block and none was ready) or an overrun (the microphone buffer overflowed). The sound system reports them, and you should log every one.

One audio fact is worth knowing by heart. A block of 480 frames at 48,000 frames a second lasts 480 / 48,000 = 10 ms. If the system keeps two blocks in flight, the audio path adds at least 20 ms of delay. A larger buffer protects against late code and adds delay you can hear. Every real-time system trades safety margin for latency.

The queue that hides the overload

Now the most common surprise. A camera makes a frame every 33.3 ms. Your vision code takes 40 ms per frame. It cannot keep up, whatever you do: in the long run it handles 33.3 / 40 = 83.3% of the frames, so 16.7% must be dropped. A queue between camera and code does not change that. It only decides which frames wait, and for how long.

A queue of one waiting frame means a worst-case wait of roughly one extra frame time. A queue of four means a frame can be about 200 ms old when it is finally processed, which is a robot reacting to where your face was a fifth of a second ago. The overload did not go away. It turned into delay. For a robot, a fresh frame beats a complete set of stale ones, so the usual policy is to keep a short queue and drop the oldest frame when it is full. Try it.

Overload a vision stage

The top row shows frames arriving every 33.3 ms. The middle row shows the stage working. The line under it shows how old each finished frame was. Drag the processing time past 33.3 ms, then change the queue.

30 ms

Illustrative: 300 frames (10 seconds) at 30 fps, processing time varying by about 30% around the value you set, seeded. When the queue is full the oldest waiting frame is dropped. The picture shows the first 40 frames; the numbers use all 300.

At 30 ms the stage keeps up: nothing drops, and each frame is about 31 ms old when it finishes. At 40 ms, about one frame in six is lost with any queue (47 or 48 of 300 here), and a longer queue only makes the survivors older: 56 ms on average with a queue of one, 150 ms with a queue of four. The honest fix is to make the code faster (Chapters 3, 7 and 8), run it on a free core (Chapter 4), or skip frames on purpose.

Put it together as a habit. Every stage logs its own latency histogram, every queue counts its drops, every loop records its wake-up lateness, and the numbers go in one place you can read during a run. With them, "sometimes it crackles" becomes "stage three missed its deadline 41 times in ten minutes, always when the logger flushed". That sentence tells you where to look.

A loop runs do_work(); sleep(2 ms) and does 0.4 ms of work. What is wrong, and what is the fix?

Chapter 3

Profiling: Where the Time Really Goes

Take a few hundred snapshots of a running program, stack them into a flame graph, and read off which function eats the budget

The audio loop must finish in 10 ms, and today it takes 3 ms on every run, which is fine. But a new feature is coming, and the budget will shrink. You open the code to find what to speed up. Three engineers name three different suspects, each with a good story. All three stories are guesses.

Programmers are bad at guessing where time goes. The slow part is rarely the clever algorithm. It is often something dull: a log call, a copy, an allocation. A profiler replaces the guess with a count.

Two ways to look: trace or sample

A tracing profiler records every function call and return, with a time stamp. The record is complete, but the recording itself takes time, and in a loop that runs 100 times a second it distorts what you measure. A sampling profiler works differently. At a fixed rate, it interrupts the program, reads which function is running and who called it, writes that down and lets the program go on. Think of a traffic camera that takes one photo a second. After an hour you do not know every car, but you know which road is busy.

Brendan Gregg, who made flame graphs popular, explains that he switched to timed sampling because tracing every call cost too much. The Linux tool for sampling is perf. A stack trace is the chain of function calls that led to the current instruction: main called audio_frame, which called log_write, which called write. One sample is one stack trace.

shell# sample all CPUs at 99 Hz with call stacks (-g) for 60 seconds
perf record -F 99 -a -g -- sleep 60
# fold the stacks, then draw the SVG (scripts from github.com/brendangregg/FlameGraph)
perf script | ./stackcollapse-perf.pl > out.perf-folded
./flamegraph.pl out.perf-folded > perf.svg

The rate 99 Hz rather than 100 Hz is the common choice to avoid sampling in lockstep with timers that tick at exactly 100 Hz. The page that gives these commands also names a catch. Many compilers leave out the frame pointer as an optimization, and then perf cannot walk the stack, so towers go missing from the graph. For C and C++, rebuild with -fno-omit-frame-pointer, or let perf use the debug information.

How to read a flame graph

A flame graph stacks all the samples into one picture. Four rules, all from Gregg's page. The vertical axis is stack depth: the root sits at the bottom and each frame above it is a function it called. The horizontal axis is not time; the frames are sorted alphabetically so equal frames merge. The width of a frame is the share of samples that contained it. And the top edge of a tower shows what was on the CPU at that moment, with everything beneath it as its callers.

So you read a flame graph by hunting for wide frames, and especially wide frames with nothing on top of them. A wide plateau is a function that does the work itself. Below is a toy flame graph of one audio frame. You take the samples; the picture builds from them.

Sample an audio loop

Choose how long to sample at 99 Hz, then press Take new samples. Pick any frame in the row of buttons to see its share of the samples and how far off that share could be. Colours: compute, memory, and input or output.

Toy program: the true shares are fixed (matmul 28%, write_syscall 22%, fft 20%, nn_infer 10%, malloc 9%, steer_weights 7%, filter 4%), and every press of the button draws a fresh set of random samples from them. The margin is 1.96 × √(p(1 − p)/n), a standard 95% estimate for a share p from n samples.

Take one second of samples and the graph looks rough: the shares of small frames wander by several points from the truth. Take sixty seconds and it settles. That wobble has a size you can compute. With n samples and a true share p, the share you estimate has a spread of about √(p(1 − p) / n). For a function that truly uses 5% of the time and 990 samples, that is √(0.05 × 0.95 / 990) = 0.0069, so about 0.7 points. A 95% range is 1.96 times that, about ±1.4 points. More samples give a tighter range, at the price of a longer run.

Reading the result and acting on it

In the toy graph, the widest plateau is matmul at 28%, which is real compute and a target for Chapters 7 and 8. But the second widest is log_write at 22%, and nobody suspected it. Writing log lines inside the hot loop costs a system call each time. Moving the log to a ring buffer that a background thread drains would save about 22% of 3 ms, 0.66 ms, leaving 2.34 ms. The malloc frame at 9% is a hint for Chapter 6. The profiler did not fix anything. It told you where to work.

What sampling cannot see

Two limits matter for robots. First, a sampling profiler by default shows only time spent on the CPU. A thread that waits for a lock, a disk or the scheduler is not running, so it never appears. That waiting often causes the tail. For it you use scheduler tracing, such as perf sched or the kernel's ftrace, which record every switch between threads. Second, sampling averages over many cycles. It shows what usually costs time, not why one particular cycle took 4 ms.

For the one bad cycle, add a cheap trigger to your own loop. Keep a small ring buffer of recent time stamps in memory. When a cycle exceeds its budget, copy the buffer out. Now every late cycle leaves a record of exactly what it did. This is the same idea as Chapter 2's counters, made precise.

The failure mode, in order. The symptom is a loop that is slow all the time. The measurement is a 60 second perf run on the real robot, under real load. The fix is whatever the widest unexpected frame says. Then profile again, because removing one cost changes the shares of all the others.

In a flame graph, one function’s frame is twice as wide as another’s. What does that tell you?

Chapter 4

Scheduling: Who Runs Now, and on Which Core

Give the control loop priority over everything else, pin it to its own core, and see exactly how much waiting that removes

The control loop's timer fires at t = 0. The loop is ready to run, and it needs only 1 ms. But the perception thread is in the middle of a long burst of number crunching on the only free core. The control loop is runnable, and it waits. When it finally runs, it is late, and the arm twitches. Nothing in the control code was slow. It simply did not get the processor.

Many threads, few cores

A computer has a few cores, each able to run one thread at a time, and it has dozens or hundreds of threads. The scheduler is the part of the operating system that decides which thread runs on which core right now. A thread is runnable when it has work to do and only needs a core. It is blocked when it waits for something else, such as a timer, a lock or data. The scheduler picks among runnable threads, and a switch from one thread to another is a context switch.

By default, Linux uses a fair-share policy called SCHED_OTHER. Its goal is to give every thread a fair slice of processor time over a period. The sched(7) manual page describes the nice value of each thread, from −20 (most favoured) to +19, where each step changes a thread's share by a factor of about 1.25. Fairness is a fine goal for a laptop. It is the wrong goal for a deadline. Fair share promises each thread a portion over time. It does not promise that any thread runs at a given moment.

Real-time policies: priority wins, always

Linux also offers real-time policies. With SCHED_FIFO, each thread has a priority from 1 (low) to 99 (high). The manual calls it "a simple scheduling algorithm without time slicing". The rules are short. A runnable thread of higher priority always takes the core from a lower one at once. A running thread keeps the core until it blocks, yields, or a higher-priority thread becomes runnable. If a higher-priority thread preempts it, it waits at the head of its priority list and resumes as soon as the higher ones block again. SCHED_RR is the same, plus a time limit per turn among equals.

Which priorities? Use the rule from Chapter 0: the shorter the period, the higher the priority. Motion at 500 Hz gets the top of your range, audio the next, vision below. The ROS 2 design article adds a practical tip: create your real-time threads at startup with a high priority, but not the maximum, so that critical kernel threads can still run above you.

There is one great danger. A SCHED_FIFO thread that never blocks will keep its core forever and starve every lower thread on it. Linux therefore throttles real-time threads. By default they may use 950,000 µs of every 1,000,000 µs, which leaves 5% of the time for everything else. Treat that safety net as a last resort, not a plan. Your real-time threads should block on their timers most of the time, as the loop in Chapter 2 does.

Pinning: choose the core yourself

CPU affinity is the set of cores a thread may use. The call sched_setaffinity sets it, and the command taskset -c 2 does the same from a shell. Pinning helps in two ways. First, the thread stops migrating between cores, so its data stays warm in that core's cache (Chapter 7). Second, you can keep other work off that core, by pinning everything else elsewhere or by reserving cores at boot (the kernel option isolcpus) so the scheduler leaves them alone. Interrupts can be steered away too, through the files under /proc/irq.

c/* run once at startup, from the thread that will run the 500 Hz loop */
cpu_set_t set; CPU_ZERO(&set); CPU_SET(2, &set);               /* core 2 only */
pthread_setaffinity_np(pthread_self(), sizeof set, &set);
struct sched_param sp = { .sched_priority = 80 };   /* high, not 99 */
pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp);
/* from a shell instead: sudo chrt -f 80 taskset -c 2 ./controller */

A program may need permission to do this: either the capability CAP_SYS_NICE or a raised real-time priority limit for its user. Check the return value, and log it loudly if the call fails. A controller that silently runs at normal priority passes every test on a quiet desk and fails on the robot.

See the difference

The device below simulates three threads in half-millisecond steps. Control needs 1 ms every 5 ms and has a 2 ms deadline after each release. Audio needs 3 ms every 10 ms. Perception is a hog that is always runnable. Choose a policy and a number of cores, and read the control loop's worst delay.

Schedule three threads

Each row is a core, drawn over 40 ms. Yellow ticks mark control releases; a red tick means that run missed its 2 ms deadline. Switch the policy, add a core, then pin control to its own.

Toy scheduler in 0.5 ms steps over 100 ms. “Fair share” is a simple round robin with 3 ms turns standing in for the real fair scheduler, which is more subtle; the FIFO rule (highest priority runs, at once) is the real one. Pinning puts control alone on core A and audio and perception on core B.

On one core with fair share, control waits behind perception and audio, up to 5 ms to start, and misses its deadline in 16 of 20 runs. Switch to SCHED_FIFO and the wait collapses to zero: control takes the core the instant it wakes. The price is paid by the others, since audio now slips behind control. With two cores and fair share, control finds the second core free in this toy and runs at once, but nothing guarantees that on a robot with dozens of threads. Pin control to its own core and its delay is zero under either policy, because nothing else is allowed there.

The failure mode, as symptom, measurement and fix. The symptom is a control loop that is late only when the robot is busy. The measurement is the wake-up lateness from Chapter 2 plotted against system load. The fix is the three steps in order: real-time priority, a pinned core, and everything else kept off that core.

A SCHED_FIFO thread at priority 90 runs a loop that busy-waits forever and never blocks. What happens to threads of lower priority on the same core?

Chapter 5

PREEMPT_RT, Locks and Priority Inversion

Find out why the highest-priority thread can still wait for the lowest, and how a real-time kernel and one lock setting remove the wait

You did everything from Chapter 4. The control thread runs at priority 90, pinned to its own core. Yet once in a while it is 9 ms late. You find the cause in one line of code: before each cycle, the control thread reads the robot's shared state under a mutex, and the logger thread, at the lowest priority, takes the same mutex to copy the state out for a log line.

A mutex is a lock that only one thread can hold at a time. A thread that wants a held lock must wait until the holder lets go. Normally that is fine, because critical sections are short. But watch what the scheduler does to a short section when a third thread arrives.

Priority inversion

Three threads. A low-priority thread L takes the lock. A high-priority thread H wakes up and wants the same lock, so it blocks. Now a medium-priority thread M, which does not use the lock at all, becomes runnable. The scheduler compares M with L. M has the higher priority, so M takes the core. L cannot run, so it cannot release the lock, so H cannot run. H, the most important thread, is held back by M, a less important one, for as long as M wants the core. This is priority inversion. The ROS 2 real-time design article describes the same case, and warns that it can stall or even deadlock a system.

Work the numbers with this timeline. L starts at t = 0 and holds the lock for 3 ms of work. H is released at t = 1 ms, needs the lock, and then needs 1 ms of work. M is released at t = 1.5 ms and needs m ms. Without a fix: L runs from 0 to 1.5 ms, then M runs for m ms, then L finishes its last 1.5 ms, and only then does H run for 1 ms. H finishes at 3 + m + 1 ms after t = 0, so 3 + m ms after its release. With m = 6 ms, that is 9 ms against a deadline of 4 ms.

The cure: priority inheritance

Priority inheritance means a lock holder temporarily takes the priority of the highest-priority thread waiting for the lock. The moment H blocks, L is promoted to H's priority. M can no longer push L aside. L finishes its critical section at t = 3 ms, drops back down, and H runs at once. The delay for H no longer depends on m at all: 3 ms after release, however long M wants to run. Move the slider and see.

Break and fix priority

H is the control thread, M is perception and L is the logger that holds the lock. The yellow line is H’s deadline, 4 ms after it wakes. Make M longer, then turn on priority inheritance.

6.0 ms

Exact for this timeline: L runs 3 ms of work holding the lock, H is released at 1 ms and needs the lock and 1 ms of work, M is released at 1.5 ms. The numbers are illustrative; the pattern is the one in the ROS 2 design article.

In real code, you ask for inheritance when you make the mutex. With POSIX threads, that is pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT). The default C++ std::mutex gives you no such promise, so a real-time thread should use a POSIX mutex configured this way, or avoid locks.

cpthread_mutexattr_t at; pthread_mutexattr_init(&at);
pthread_mutexattr_setprotocol(&at, PTHREAD_PRIO_INHERIT);   /* the holder inherits the waiter's priority */
pthread_mutex_t state_lock; pthread_mutex_init(&state_lock, &at);

The best lock is no lock

Inheritance limits the damage, but the control thread still waits for the logger's critical section. The ROS 2 article lists better answers: avoid blocking primitives in the real-time path, or use lock-free structures. The usual design gives each shared item one writer and one reader. The control thread writes its state into a fixed-size buffer and moves on. The logger reads from that buffer in its own time. Chapter 9 builds one such queue in full.

Why the kernel matters too

All this assumes that a high-priority thread can take the core the moment it wakes. In an ordinary Linux kernel, that is not always true. Some kernel code runs with preemption off: interrupt handlers, and regions guarded by spinlocks, locks whose waiters burn the core in a loop rather than sleep. While that code runs, even a priority-99 thread must wait. Those waits are short but unbounded in principle, and they show up in cyclictest as rare large maximums.

PREEMPT_RT is a set of kernel changes that shrinks those regions. The kernel documentation names the main ideas in its real-time section: spinlocks become sleeping locks that a thread can be preempted inside, locks use priority inheritance, and interrupt handlers run as threaded interrupts, ordinary kernel threads with a priority you can rank above or below your own. The result is not a faster kernel. It is a more predictable one, with a lower and better bounded worst-case wake-up delay.

Two cautions. A real-time kernel does not rescue slow user code. The ROS 2 article says the same: you need a real-time operating system and deterministic user code, and neither alone is enough. And the kernel cannot see your locks. If your program takes a shared lock without inheritance, or calls something that blocks, the tail returns. A good rule for the real-time thread is simple: it never calls anything that might wait on a thread of lower priority.

The failure mode, as symptom, measurement and fix. The symptom is a high-priority thread late by a long, irregular amount while it is not using much CPU. The measurement is a scheduler trace (Chapter 3) showing the thread blocked on a lock whose holder is runnable but not running. The fix is inheritance on that lock, then lock-free handoff, then a real-time kernel for the delays you do not control.

The control thread (high priority) waits for a lock held by the logger (low). A perception thread (medium, no lock) keeps running. Which change guarantees the control thread waits only for the logger’s short section?

Chapter 6

Memory in the Hot Loop: malloc and Page Faults

Move every allocation out of the loop, lock and prefault memory at startup, and count page faults to prove the loop stays quiet

The voice crackles every few seconds, and it always happens in the same place: a function that builds the next audio block. The code looks innocent. It makes a temporary buffer, fills it, hands it over and lets the buffer go. Ten lines. The profile from Chapter 3 shows malloc at 9% of the loop. The average is small. The tail is not.

What a page fault is

Your program sees a tidy range of addresses. Behind that, the operating system hands out real memory in blocks called pages, usually 4 KiB each (4,096 bytes). The mapping from your addresses to real pages is built lazily. When you first touch an address whose page is not yet in place, the processor stops your code and calls the kernel. This stop is a page fault. The kernel finds a page, clears it to zero so you cannot see old data, wires it into your map, and lets you continue.

If the page was already in memory somewhere, this is a minor fault, and it takes microseconds. If the page has to be read from disk or swap, it is a major fault, and it can take milliseconds. The ROS 2 real-time article names page faults as a cause of non-determinism for this reason: the processor stalls until the page is loaded.

What malloc does that you cannot see

malloc gives you a block of memory. How long it takes depends on what is free. The allocator may find a block quickly, or search a long list, or ask the kernel for more memory, which means page faults when you first write. The same article says the time to find a free block is unbounded. It also notes that heap fragmentation grows over time. Worse for a multi-threaded robot: the allocator keeps shared state under a lock, so your real-time thread can wait on a lock held by a slow thread. That is the priority inversion of Chapter 5, hiding inside malloc.

Allocation hides in many places beyond the word malloc: a vector that grows with push_back, a string built by joining, a lambda stored in a std::function, a log line formatted into a fresh buffer, a thread created on demand, a Python list or object. The rule for the real-time path is blunt. Allocate nothing while the loop runs.

The recipe: do it all before the loop

The ROS 2 article gives the recipe, and each step has a reason.

  1. Allocate first. Make every buffer, queue and object pool you need at startup, with fixed sizes. Use stack objects, object pools or a bounded-time allocator such as TLSF. In the loop you only reuse.
  2. Lock memory. Call mlockall(MCL_CURRENT | MCL_FUTURE). The manual says this locks all pages mapped now and all pages mapped later, and that after success all mapped pages are guaranteed to be resident in RAM, so they cannot be swapped out. Unprivileged programs can hit the limit RLIMIT_MEMLOCK and get an error, so check the return value.
  3. Prefault. Locked is not the same as touched. A fresh page still faults on first touch. So walk every buffer once at startup, writing one byte per 4 KiB, and use up some stack by declaring and clearing a large local array.
  4. Stop the allocator from giving memory back. With glibc you can disable trimming and mmap use through mallopt, so freed memory stays in your process.
  5. Move slow work off the path. Disk and console output belong to the start, the end or a non-real-time thread.
c/* startup, before the real-time loop begins */
mlockall(MCL_CURRENT | MCL_FUTURE);                 /* never swap out, now or later */
mallopt(M_MMAP_MAX, 0);                          /* no mmap for big blocks */
mallopt(M_TRIM_THRESHOLD, -1);                   /* never return heap to the OS */
static float pool[POOL_N][BLOCK];                  /* all buffers, fixed size, allocated once */
for (int i = 0; i < POOL_N; i++) memset(pool[i], 0, sizeof pool[i]);   /* prefault: touch every page */
char stack_burn[256 * 1024]; memset(stack_burn, 0, sizeof stack_burn);   /* prefault the stack */
/* in the loop: take a block from a free list in O(1), return it when done */

Try each stage of the recipe. The buffer size sets how many pages one cycle touches. Turn on memory pressure, which stands in for a busy system that wants your idle pages back.

Allocate, reuse, or lock

Each bar is one of 300 cycles against a 1 ms deadline. Pick how the buffer is handled, change its size, and switch memory pressure on and off.

256 KiB

Illustrative model, seeded: 0.3 ms of work, 4 KiB pages, 2 µs per minor fault (including clearing the page), an allocator stall of 0.4 to 1.2 ms in 3% of malloc cycles, and under memory pressure a major fault of 3 to 6 ms in 1.2% of unlocked cycles. Only the pattern is the lesson’s claim.

With the default 256 KiB buffer, that is 64 pages, and at 2 µs per fault one cycle spends 0.128 ms on faults alone, 12.8% of the budget, every cycle, before any allocator stall. Allocating once removes this and the stalls, but without locking, memory pressure brings back rare, huge major faults. The locked and prefaulted version has none of them, and its startup pays the 64 faults once, before the loop begins.

Prove it with a counter

Do not trust the recipe. Check it. Call getrusage(RUSAGE_SELF, ...) before and after a long run of the loop, as the ROS 2 article suggests, and compare the fields for minor and major page faults. A correct real-time loop shows no change in either. Put that check in a test that runs on every build, since one innocent change can add an allocation back.

The failure mode, as symptom, measurement and fix. The symptom is a rare, large delay with no scheduler cause. The measurement is the page-fault counters rising during the loop, or malloc in a trace taken during a late cycle. The fix is the five-step recipe, applied at startup.

A real-time loop calls mlockall at startup but still shows rising minor page faults during the first seconds of the run. What most likely explains it?

Chapter 7

Cache-Aware Layout: Moving Fewer Bytes

Learn that memory arrives in 64-byte lines, then reorder your data so every line you load carries only what the loop needs

The robot tracks a sound source with a cloud of 4,096 guesses, called particles. Each particle holds a position, a velocity, a weight, an age and some flags. Every cycle, one loop adds up all the weights to scale them. The loop is three lines. It runs at the speed of memory, not the speed of the processor, and nothing in the profile of Chapter 3 shows why: the time sits in one line, sum += p[i].weight.

The processor outruns memory

A processor can do arithmetic far faster than main memory can deliver numbers. To bridge the gap, hardware puts small, fast memories called caches between them. When you read an address, the processor first looks in the nearest cache. A hit is cheap. A miss goes down to the next level and finally to main memory, which is slow. Ulrich Drepper's paper gives a simple model: if main memory takes 200 cycles and cache takes 15, code that touches 100 data items 100 times each spends 2,000,000 cycles on memory with no cache and 168,500 cycles when all the data stays cached, an improvement of 91.5%.

The key fact is the unit of transfer. Memory does not move one number at a time. It moves a cache line: a block of 64 bytes on current machines, as Drepper notes. Touch one byte and the whole 64-byte line comes in. You pay for the line, not for the byte.

Array of structs, struct of arrays

Now count. Suppose each particle is a 64-byte struct, one per line, and you want only the 4-byte weight. This layout is called an array of structs, written AoS: the particles sit in a row, each with all its fields. To read 4,096 weights you load 4,096 lines, which is 256 KiB, and you use 4 of every 64 bytes. You moved sixteen times more data than you needed.

Flip the layout. Keep all the weights together in one array, all the ages in another, all the x positions in another. This is a struct of arrays, SoA. The 4,096 weights now take 4,096 × 4 = 16,384 bytes, so 16,384 / 64 = 256 lines. Every line is full of useful weights. You load 256 lines instead of 4,096, sixteen times fewer.

The effect is bigger than the ratio suggests. A typical first-level data cache holds 32 KiB, which is 512 lines. The SoA weights fit inside it, so on the next cycle they are already there. The AoS lines, 256 KiB of them, push each other out. Try the arithmetic with other sizes.

Count the cache lines

The two strips show the first 128 bytes of memory in each layout; each small square is 4 bytes, and the bright ones are the weight field. The bars count the 64-byte lines needed to sum all weights. Change the struct size and the number of particles.

4,096

Exact counts for a loop that reads one 4-byte field from every element, with 64-byte lines and each struct starting on a line boundary where it is 64 bytes or larger. The 32 KiB first-level cache (512 lines) is a common size, not a fact about your robot. Time is not shown: it depends on the processor and its prefetcher.

With 64-byte structs and 4,096 particles the bars show 4,096 against 256 lines. Switch to 16-byte structs and AoS improves to 1,024 lines, only four times worse than SoA, because four structs share a line. Switch to 128 bytes and AoS is no worse in lines (one per struct) but the structs now sit two lines apart, so more of the cache is wasted skipping. The lesson is not that SoA always wins. The lesson is to count the useful bytes per line.

When the layout choice flips

SoA wins when a loop touches one or two fields of many items. AoS wins when you always use all the fields of one item together, such as a single joint's position, velocity and torque in one control step. The fix for the in-between case is hot and cold splitting: keep the few fields the hot loop reads in one compact struct, and move rarely used fields (names, debug flags) elsewhere.

Two more rules from the same facts. First, walk memory in order. The hardware notices a sequential pattern and loads the next lines before you ask. A linked list or a tree of separate allocations defeats it, since each step is a new address, so in hot loops prefer flat arrays. Second, beware false sharing. If two threads on two cores write to different variables that share one 64-byte line, the line bounces between the two caches on every write, even though the threads never touch each other's data. Give each thread's counters their own line with alignas(64).

c/* array of structs: 64 B per particle, a sum of weights loads 4,096 lines */
struct P { float x[3], v[3], weight, age; int id, flags; char pad[24]; };
struct P aos[4096];

/* struct of arrays: the weights are contiguous, the same sum loads 256 lines */
struct Particles { float *x, *y, *z, *weight, *age; };
float sum_weights(const float *w, int n) { float s = 0; for (int i = 0; i < n; i++) s += w[i]; return s; }

/* false sharing guard: one counter per thread, each on its own line */
struct alignas(64) Counter { long n; };

This also explains an old advice from Chapter 4: pin the thread. A thread that migrates to another core arrives at a cold cache and pays for every line again.

The failure mode, as symptom, measurement and fix. The symptom is a loop that is slow all the time, with a simple body, and that gets much slower when the data grows past the cache. The measurement is perf stat with the cache-miss counters, plus the wall time as you double the item count. The fix is a layout change: fewer bytes per item the loop needs, contiguous, aligned, and no pointer chasing.

A loop reads only the 4-byte weight of each of 1,024 particles. Each particle is a 64-byte struct. How many cache lines does it load, and how many would a packed array of weights need?

Chapter 8

Vector Instructions: Eight Numbers per Step

Let one instruction work on several numbers at once, and learn what stops the speed-up from growing with the register width

The robot listens with a ring of eight microphones. Every 10 ms, each microphone delivers 480 samples. The audio loop multiplies every sample by a gain or a filter weight: 8 × 480 = 3,840 multiplications per block. Done one at a time, that is 3,840 steps for a task that is the same operation repeated. A modern processor has hardware to do many of them in one step, and most code never uses it.

One instruction, many numbers

A normal instruction works on one number. SIMD, short for single instruction, multiple data, works on a short row of numbers held in one wide register. Each position in the row is a lane. A 128-bit register holds four 32-bit floats, so one multiply instruction does four multiplications. A 256-bit register (AVX2 on many desktop and server chips) holds eight. A 512-bit register (AVX-512) holds sixteen. The 128-bit form is called SSE on x86 and NEON on ARM, and many robot computers use ARM.

Think of a checkout worker who scans one item at a time, against a worker with a wide scanner that reads a whole row of barcodes in one pass. The goods are the same. The step count drops by the width of the scanner, provided the items are lined up in a row and the shelves can supply a row at a time.

Getting the compiler to do it

You rarely write vector code by hand. The compiler's auto-vectorizer turns a simple loop into vector instructions, if the loop looks safe to it. The loop needs a countable length, consecutive memory access (stride one, which is why Chapter 7's struct-of-arrays layout matters), no step that depends on a previous step's result, and pointers that cannot overlap. You tell the compiler about overlap with restrict in C. You turn the feature on with -O3, and you allow the target's instructions with a flag such as -march=native or -mavx2. Take care: a binary built for AVX2 stops with an illegal instruction on a chip that lacks it, so build on, or for, the robot's own processor.

Do not assume it worked. Ask the compiler. GCC prints its decisions with -fopt-info-vec, and clang with -Rpass=loop-vectorize. If a hot loop is missing from that report, find out why before you reach for hand-written code.

c/* scalar: 3,840 multiplies, one per step */
void gain(float *restrict out, const float *restrict in, float g, int n) {
    for (int i = 0; i < n; i++) out[i] = in[i] * g;    /* -O3 -mavx2 turns this into 8 lanes per step */
}
/* the same by hand with AVX2 intrinsics, 8 floats per step */
void gain_avx2(float *out, const float *in, float g, int n) {
    __m256 vg = _mm256_set1_ps(g); int i = 0;
    for (; i + 8 <= n; i += 8)
        _mm256_storeu_ps(out + i, _mm256_mul_ps(_mm256_loadu_ps(in + i), vg));
    for (; i < n; i++) out[i] = in[i] * g;               /* the tail: n not a multiple of 8 */
}

Why wider is not always faster

Here is the catch the device below makes visible. A vector multiply cannot start until its numbers arrive. Every loop has two costs: the cycles to compute, and the cycles to move the data in and out. The loop takes whichever is larger. Wider lanes shrink only the compute side.

Take our block. It reads 3,840 floats (15,360 bytes) and writes the same, so it moves 30,720 bytes. Suppose, for illustration, that data in the first-level cache moves at 64 bytes per cycle. Then memory needs 30,720 / 64 = 480 cycles. Scalar compute needs 3,840 cycles, so the loop is compute-bound and takes 3,840. With four lanes, compute drops to 960. With eight, to 480, which equals the memory time. With sixteen, compute is 240 cycles, but memory still needs 480, so the loop takes 480: eight times faster than scalar, not sixteen.

Now suppose the data sits in main memory and arrives at 8 bytes per cycle (also illustrative). Memory needs 30,720 / 8 = 3,840 cycles. Every column, from scalar to sixteen lanes, takes 3,840 cycles. Vector instructions give nothing, since the processor is waiting for data. This is the same message as Chapter 7 from the other side: first fix the bytes moved, then widen the arithmetic.

Widen the lanes until memory says stop

For each width, the blue bar is compute cycles and the warm bar is memory cycles. The loop takes the longer one. Choose a width and where the data lives, then add microphone channels.

8

Illustrative model: one vector multiply per cycle, 480 samples per channel per block, each sample read and written as a 4-byte float, 2 GHz clock. Real chips overlap, pipeline and prefetch, so measure your own; the max(compute, memory) shape is the point.

With 8 channels in cache, moving from 8 to 16 lanes changes nothing: both take 480 cycles. Add channels and compute grows with the data, but so does memory, and the ratio between them stays. Switch to main memory and every bar collapses to the same height. That is the signature of a loop that is bound by memory, not by arithmetic.

Three audio traps

Floats not divisible by the lane count leave a tail, which the compiler handles with a short scalar loop or a mask. A sum is harder: adding floats in a different order changes the rounding, so the compiler will not reorder a sum on its own unless you allow it with -ffast-math, a flag with other side effects. The safe route is to write the reduction with several partial sums yourself.

The third trap is special to audio. Very tiny floating-point numbers, called denormals, can make some processors run an operation many times slower. A filter whose output decays toward zero will eventually produce them, and the loop slows down just as the sound fades to silence. The usual cure is to set the processor's flush-to-zero mode at thread start, so tiny values become exact zero.

The failure mode, as symptom, measurement and fix. The symptom is an arithmetic-heavy loop that the profiler shows as one hot, simple function. The measurement is the compiler's vectorization report plus a timing run with data in cache and out of it. The fix is a contiguous layout, then the right flags, then intrinsics for the one loop that still misses, then a check that memory is not the limit.

A loop needs 960 compute cycles with 4 lanes and 1,920 memory cycles. You move to 8 lanes. About how long does the loop take?

Chapter 9

Zero-Copy Pipelines: Pass the Handle, Not the Frame

Count the bytes a camera pipeline copies, then hand frames between stages as small handles into one shared buffer

The robot's camera produces 1080p video at 30 frames a second. The vision pipeline has five stages: capture, preprocess, inference, overlay and publish. A profile shows the processor busy, yet no stage does much arithmetic. The wide frame in the flame graph is memcpy, the function that copies bytes. The pipeline spends its budget moving the same picture from one place to another.

How big is a frame, really?

One 1080p frame is 1,920 × 1,080 pixels, and an RGB pixel takes 3 bytes. So a frame is 1,920 × 1,080 × 3 = 6,220,800 bytes, about 6.2 MB. At 30 frames a second that is 186.6 MB moving every second, for each time it is copied once. A copy reads the frame and writes it, so it moves the bytes twice through memory. Four copies in a row move 4 × 2 × 186.6 = about 1.49 GB a second, before any real work, on a small computer that shares its memory bus with the audio loop, the motion loop and the network.

Where do the copies come from? Each stage may want its own private input, so it clones it. A message system may serialize a frame into a byte string and rebuild it on the other side. Two programs in separate processes have separate address spaces, so data must be moved to cross. A format change copies. Sending a frame to the graphics chip copies, unless the memory is shared. Each is reasonable alone. Together they eat the budget.

The idea: one frame, many readers

A zero-copy pipeline writes each frame into memory once, and then passes around a handle: a small number that says which buffer holds it, where it starts and how long it is. A handle is a few bytes. Handing it over costs nothing like a frame's 6.2 MB. Think of a library. You do not photocopy a book for every reader; you tell each reader the shelf number.

This needs three things. First, the buffer must live in memory that all stages can see: a block in one process, or shared memory between processes. Second, the data must be plain: a fixed layout with no internal pointers, since a pointer into one program's heap is meaningless to another. Third, you need an ownership rule. A common one is a buffer pool: a fixed set of frame slots made at startup (Chapter 6). The camera fills a free slot. Stages take a read-only reference. When the last one finishes, the slot returns to the free list. Nobody writes into a slot someone else is still reading.

The hardware helps. Linux video capture can place frames straight into memory your program maps, and it can export a buffer as a file handle that a graphics chip or video encoder imports without copying. ROS 2 offers loaned messages for the same purpose: the middleware lends the publisher a message in its own memory, so the publisher writes once and subscribers read in place. It works for fixed-size message types and for middleware with a shared-memory transport; check what your stack supports.

Count the bytes a pipeline moves

The boxes are five stages at 30 frames a second. Each arrow either copies the frame (a warm block) or passes a handle (a green dot). Pick a resolution, choose how many arrows copy, or switch on zero-copy.

4

Frame size is exact: width × height × 3 bytes, at 30 frames a second. The copy speed (5 GB/s, counted one way) and the 4 GB/s bandwidth you can spare for copies are illustrative, not measured on any robot.

At 1080p with four copies, the pipeline spends 4 × 1.24 = 5.0 ms of every 33.3 ms frame just copying, and moves 1.49 GB a second. At 4K the same pipeline spends about 19.9 ms per frame copying, three fifths of the budget, and moves nearly 6 GB a second, more than the budget line. With zero-copy on, the copy time is zero at every resolution. The frame is written once, by the camera.

The same idea for audio: a lock-free ring

Audio blocks are small, so the aim there is not the bytes but the lock. A ring buffer is a fixed array used as a circle: the writer fills slots in order, the reader empties them in order, and both wrap around at the end. With exactly one writer and one reader, you can build it with no lock at all. The writer owns the write index, the reader owns the read index, and each only reads the other's. The real-time thread never waits for the non-real-time one, which removes the priority inversion of Chapter 5.

c++template<typename T, size_t N>   // N is a power of two; everything is allocated once, up front
struct Ring {
    T buf[N];
    alignas(64) std::atomic<size_t> head{0};   // written only by the producer
    alignas(64) std::atomic<size_t> tail{0};   // written only by the consumer; own line avoids false sharing
    bool push(const T& v) {
        size_t h = head.load(std::memory_order_relaxed);
        if (h - tail.load(std::memory_order_acquire) == N) return false;   // full: drop and count it (Chapter 2)
        buf[h & (N - 1)] = v;
        head.store(h + 1, std::memory_order_release);              // publish the data before the index
        return true;
    }
    bool pop(T& out) {
        size_t t = tail.load(std::memory_order_relaxed);
        if (t == head.load(std::memory_order_acquire)) return false;      // empty
        out = buf[t & (N - 1)];
        tail.store(t + 1, std::memory_order_release);
        return true;
    }
};

The acquire and release markers are the whole trick. The writer's release store says "everything I wrote into the slot is visible before this new index is". The reader's acquire load says "if I see the new index, I also see that data". Without them, the reader could see the index move but read a stale slot. The two indexes sit on separate 64-byte lines for the reason in Chapter 7: if they shared a line, the two cores would fight over it on every push and pop.

Hidden copies are easy to introduce and hard to see. An image-library call that "clones" a frame, a type conversion from bytes to floats, a message that is serialized to text for a log, a Python array turned into a list: each one copies. The way to find them is Chapter 3. Profile the pipeline, and look for memcpy and conversion functions as wide frames.

The failure mode, as symptom, measurement and fix. The symptom is high processor and memory-bus load with little useful arithmetic, and frame latency that grows with resolution. The measurement is a flame graph that shows memcpy wide, plus the byte count per stage. The fix is one buffer from a pool, handles between stages, and a single-writer ring where data crosses a thread boundary.

A 720p RGB frame is 1,280 × 720 × 3 bytes. At 30 frames a second, how much data does one copy of every frame move per second (counting one direction)?

Chapter 10

Field Guide: The Numbers, the Checklist and the Core Loop

Keep the numbers, the order of work and one complete real-time loop, then follow the links to the sources and to deeper lessons

You can now follow a late cycle from symptom to cause to fix. A control loop is late because it waited: for the scheduler (Chapters 4 and 5), for memory (Chapter 6), for data to arrive (Chapter 7), or because it did too much work (Chapters 3, 8 and 9). You find which by measuring (Chapters 1 to 3), and you fix one cause at a time.

The one-paragraph summary

A robot runs several periodic loops on shared compute. Each loop has a period and a deadline, and the slowest cycles, the tail, decide how smooth the robot looks. Measure with monotonic clocks, stamps from the source, counters for drops and a long, busy run. Profile with a sampling profiler and read the flame graph by width. Give the control thread a real-time priority and a pinned core, use priority-inheriting locks or no locks, and run a real-time kernel for the delays you cannot control. Allocate, lock and prefault memory before the loop. Lay data out so each cache line carries only what the loop needs, let the compiler use vector instructions, and pass handles instead of frames.

The numbers that matter

WhatNumberWhy it matters
The running robot’s loopsmotion 500 Hz (2 ms); audio 100 Hz (10 ms, 480 samples at 48 kHz); vision 30 Hz (33.3 ms)Utilization is work time divided by period
Rate-monotonic guaranteen(21/n − 1): 100% for 1 loop, 82.8% for 2, 78.0% for 3, 69.3% for many (Liu and Layland, 1973)Under it, every deadline is proven safe
On-time rate to misses99% at 500 Hz is 5 misses a second; 99.9% is 30 a minuteAlways convert a percentage into a rate
Sampling profileperf record -F 99 -a -g; 990 samples gives about ±1.4 points for a 5% shareLonger runs tighten every share
SCHED_FIFOpriority 1 to 99; no time slicing; real-time throttle 950,000 of every 1,000,000 µsPriority removes waiting; a spinning FIFO thread starves the rest
Nice values−20 to +19, a factor of about 1.25 in share per stepFair share promises no wake-up time
Page4 KiB; a 256 KiB buffer is 64 pagesEach first touch is a page fault
Cache line64 bytes; main memory 200 cycles against cache 15 in Drepper’s modelYou pay for lines, not bytes
Drepper’s worked case100 items touched 100 times: 2,000,000 cycles uncached, 168,500 cached (91.5% less)Caches are the reason layout matters
AoS against SoA, summing a 4-byte field4,096 particles of 64 bytes: 4,096 lines against 25616 times fewer lines
SIMD lanes for 32-bit floats4 (SSE, NEON), 8 (AVX2), 16 (AVX-512)Speed-up stops where memory time begins
1080p RGB frame6,220,800 bytes; 186.6 MB/s per copy at 30 fpsCopies add up; handles do not

The checklist, in order

  1. Write down the budget. Period, deadline and work time for every loop. Add the utilizations per core.
  2. Measure the tail. Wake-up lateness and loop time, as percentiles and a maximum, over a long run with the whole robot busy.
  3. Count the losses. Sequence numbers, queue drops, xruns, page faults. Keep them where you can read them.
  4. Profile. A 60 second perf run. Read the widest frames. Rebuild with frame pointers if the graph has holes.
  5. Split the loops. Control thread to a real-time priority and its own core. Everything else off that core.
  6. Check every lock. Priority inheritance on, or replace with a single-writer ring. No blocking calls in the real-time path.
  7. Quiet the kernel. Try a PREEMPT_RT kernel and compare the cyclictest maximum under load.
  8. Clean the memory. Allocate at startup, mlockall, prefault, then check that the page-fault counters do not move.
  9. Shrink the data. Struct of arrays, hot and cold split, contiguous, no false sharing.
  10. Vectorize, then check memory. Read the vectorization report. Stop widening when the loop is memory bound.
  11. Remove copies. A buffer pool and handles between stages.
  12. Measure again. Keep a test that fails when the tail, the drops or the page faults grow.

The core as code

Here is one complete real-time loop that applies the checklist. It locks memory, prefaults the stack, pins itself, takes a real-time priority, sleeps to absolute times, and records how late each wake-up was. It is a sketch: do_work stands for your control step, and real code would check and log every return value.

c#define _GNU_SOURCE
#include <sched.h> <pthread.h> <sys/mman.h> <sys/resource.h> <time.h> <string.h> <stdio.h>
#define PERIOD_NS 2000000L                        /* 500 Hz */
static long late_us[64];                          /* histogram: bucket = lateness in 50 us steps */

int main(void) {
    mlockall(MCL_CURRENT | MCL_FUTURE);                 /* Ch 6: no swapping, now or later */
    char burn[256 * 1024]; memset(burn, 0, sizeof burn);     /* Ch 6: prefault the stack */
    cpu_set_t cs; CPU_ZERO(&cs); CPU_SET(2, &cs);                   /* Ch 4: pin to core 2 */
    pthread_setaffinity_np(pthread_self(), sizeof cs, &cs);
    struct sched_param sp = { .sched_priority = 80 };      /* Ch 4: high, not 99 */
    pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp);

    struct rusage a, b; getrusage(RUSAGE_SELF, &a);          /* Ch 6: page faults before */
    struct timespec next; clock_gettime(CLOCK_MONOTONIC, &next);
    long worst = 0, missed = 0;
    for (long i = 0; i < 500L * 600; i++) {                  /* ten minutes */
        next.tv_nsec += PERIOD_NS;
        if (next.tv_nsec >= 1000000000L) { next.tv_nsec -= 1000000000L; next.tv_sec++; }
        clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);   /* Ch 2: absolute time, no drift */
        struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now);
        long late = (now.tv_sec - next.tv_sec) * 1000000000L + (now.tv_nsec - next.tv_nsec);
        if (late > worst) worst = late;
        int k = (int)(late / 50000); late_us[k > 63 ? 63 : k]++;     /* Ch 1: keep the whole tail */
        do_work();                                         /* no malloc, no printf, no blocking lock */
        if (late > PERIOD_NS) missed++;                  /* woke more than a full period late */
    }
    getrusage(RUSAGE_SELF, &b);
    printf("worst %ld us, missed %ld, minor faults %ld, major faults %ld\n",
           worst / 1000, missed, b.ru_minflt - a.ru_minflt, b.ru_majflt - a.ru_majflt);
}

Where this sits

This lesson is the performance layer under every robot behaviour. The control laws themselves are in trajectory tracking with PID and LQR and control for navigation. They assume a loop that runs on time, and this lesson is how you make that true. The wider embedded story is in embedded real-time systems and real-time operating systems, and the Linux side in embedded Linux.

Keep going

Sources and credit

This page was written from primary sources, with no course slides behind it. Every factual claim about a tool or a number comes from one of these, and the toy numbers on the devices are labelled illustrative.

Further reading named in the text, not quoted: the manual pages clock_nanosleep(2) and mallopt(3); the ROS 2 tutorial on loaned messages; and Agner Fog’s Optimizing software in C++ for vector instructions. The vector widths in Chapter 8 are standard architecture facts; the model in that chapter is illustrative.

The takeaway. Real-time means a measured, bounded worst case. Find the tail first. Then remove its causes one at a time, in the order the checklist gives, and keep a test that tells you when one comes back.
Your 500 Hz control loop shows a maximum wake-up lateness of 6 ms in a ten-minute busy run, while the median is 0.05 ms. Which first step does the checklist call for?

Now press Teach and explain, from memory, how a 500 Hz loop gets from a 6 ms tail to an on-time cycle. Then go back to the three setups at the top, set the load to 100%, and say which chapter explains each step from Default to Fully tuned.

Robot Real-Time Performance
Embedded real-time systems · Embedded Linux · Back to Gleams