The Real-Time Mental Model

Once a second, a logger stalls a 1 kHz arm controller for 3 ms. That one 4 ms cycle makes the velocity estimate four times too big, and the safety stop trips. The mean cycle time reads 1.003 ms, inside its spec.

Drag the logger's stall, then let the loop outrank the logger. The mean barely moves either way; the worst cycle decides. Then we build, piece by piece, deadlines, tail percentiles, test length, fixed rates, schedules and the latency budget of the whole track.

You need a sorted list, an average and a little Python. We build the rest from zero.

Lesson 10 of the Robotics Engineering track, the last one. Before: Lesson 9, Downstream Perception. Lessons 1 to 9 built a robot that knows where it is. This lesson asks when each answer arrives, and ties the track together in Chapter 7.

Stall one cycle, watch the arm trip

3000 µs

Illustrative 1 kHz joint loop: 300 µs of compute per cycle, a true joint speed of 1 rad/s, and a velocity estimate that divides each angle change by the assumed 1 ms. The safety limit (twice the normal estimate) is a made-up number. Mean and worst are over 1,000 logged cycles with one stall.

Chapter 0

The Arm That Trips Once a Second

Average a thousand cycles and watch the one that matters disappear

A robot arm's joint controller runs every millisecond. Each cycle reads the joint angle, estimates the speed, and commands a torque. The logs say the mean cycle time, the time from one loop start to the next, is 1.003 ms. The spec allows 1% either way.

And once a second the arm lurches and the safety stop cuts power. Nobody can make it happen on demand. Every average says the system is healthy.

The cause is one cycle in a thousand. A background logger holds the CPU for 3 ms, so that cycle lasts 4 ms. The speed estimate still divides by 1 ms, so it comes out four times too big. The arm brakes hard against a motion that is not there.

Average a thousand cycles

Each blue dot is one logged cycle; red dots are 4 ms cycles that trip the arm. Purple lines mark the mean, the median and the maximum. Drag the share of slow cycles.

0.1%

Illustrative: healthy cycles spread evenly over 980 to 1,020 µs, slow cycles at exactly 4,000 µs, spaced evenly. The yellow line is the made-up trip limit of 2 ms.

Do it by hand once. Ten cycle times in microseconds, sorted:

980, 990, 995, 1000, 1005, 1010, 1015, 1020, 1030, 4000

The sum is 13,045, so the mean is 1,304.5 µs. It describes no cycle that happened: nine sit near 1,000 and one sits at 4,000. The median, the middle value, is (1,005 + 1,010)/2 = 1,007.5 µs. It never sees the slow cycle. Only the maximum, 4,000 µs, does.

The standard deviation is no rescue. Here it is 898.6 µs, and mean plus one deviation is 2,203 µs: a time no cycle took. Drop the slow cycle and the deviation falls to 14.7 µs. One cycle decides it, and the number still does not say how long that cycle took.

Symptom: every average-based check passes, yet the robot trips on a steady rhythm.

Measure: plot the maximum cycle time, or a high percentile, against the limit. Log the time of each trip.

Fix: a fault with a period is a task with that period. Find it with the trip times (Chapter 8), then stop it reaching the loop (Chapter 6).

The road

  1. Deadlines: hard, firm and soft, and what a miss costs.
  2. The tail: latency, jitter, WCET and the percentile that sees the fault.
  3. Soak length: how long to look before a rare fault shows.
  4. The Δt in the code: why a late cycle becomes a wrong torque.
  5. Same mean, opposite fate: jitter destabilises a loop.
  6. Will it fit: utilisation, the rate-monotonic bound, response time.
  7. The whole track: one latency budget from camera to motor.
  8. Find the culprit: what to log and how to read it.
  9. Showcase: jitter a live loop until it misses.
  10. Field guide: the numbers, the code, the track in one table.
The arm trips once a second. Mean cycle time is 1.003 ms and the median is 1.000 ms. What is the most useful next number?

Chapter 1

Hard, Firm and Soft: What a Miss Costs

Draw each deadline as the value of a late answer, then price a miss rate

A deadline is the time D by which a result must arrive to be useful. A real-time task is one whose result is wrong if it is late, even when the arithmetic is right. The useful question is what a late result is worth.

Draw that worth as a value function V(t): the value of a result that arrives at time t. Before D, every kind is worth 1. After D they split three ways.

Price a late answer

The three curves share the on-time shelf, then split at the deadline D. Drag the arrival time, then the miss rate, and read the average value of each kind.

1.50 D
2.0%

Illustrative soft window τ = 2 D, so a result one D late keeps half its value. We draw hard in red after D because its late branch is a failure.

Once you know the shape, price a miss rate. Call the share of results that arrive late p, and the value a late result keeps vlate. On-time results are worth 1.

Say it aloud

The expected value of V equals one minus p times the quantity one minus v-late.

E[V]
the expected value of V the average worth of one result over many cycles, from 0 to 1.
p
p the miss rate: the share of results that arrive after D.
vlate
v-late what a late result is still worth: 0 for firm, between 0 and 1 for soft.
In plain words

Each late result loses 1 minus v-late of its value. A share p of results are late. Subtract p times that loss from a perfect 1.

With numbers

With made-up numbers, p = 0.02. Firm, v-late = 0: E[V] = 1 − 0.02 = 0.98. Soft, v-late = 0.75: E[V] = 1 − 0.02 × 0.25 = 0.995. The firm task loses four times as much at the same miss rate.

Turn it around to write a spec. To keep E[V] at 0.99 or more, a firm task may miss 1% of the time and the soft one 4%: p ≤ 0.01/(1 − vlate). A hard task has no such budget. Its late value is a disaster, so its spec is a zero-miss proof, not an average.

Symptom: a "minor" firm task runs late and the whole robot faults.

Measure: timestamp each stage's input and output. If the control loop's start jumps whenever the detector is late, a blocking call joined them. A detector frame that ends at 45 ms against 33 ms, read at the control tick of 40 ms, stalls that tick for 5 ms and skips four.

Fix: read the newest finished result from a slot that never blocks, and check its timestamp. The firm miss then costs one stale frame.

A 30 Hz detector is sometimes 10 ms late. The planner reuses the previous target when no fresh one has arrived. What kind of deadline is this?

Chapter 2

The Tail: Latency, Jitter, WCET and the Percentile

Read a percentile as a position in a sorted list, and pick the one that matches the fault

Three words name the numbers that decide a miss. Latency is how long one operation takes; it has a whole distribution. Jitter is how much it varies cycle to cycle, quoted as peak to peak or as a standard deviation. The WCET, the worst-case execution time, is the largest time the operation can ever take. Check a hard deadline against the WCET.

The tool that reads a tail is the percentile. The p99 is the value that 99% of cycles stay under. Sort the cycle times, and the percentile is a position in that list.

Walk the rank up the sorted list

Twenty cycle times, sorted: nineteen healthy, one at 4,000 µs. The warm pointer is the rank of the percentile you pick; the purple dot is the value read between its two neighbours. Drag q.

p99.0

The twenty samples below the device. The rule is NumPy's default linear method.

Number the sorted list from s[0] to s[n − 1]. Call the percentile level q. The rank r = (q/100)(n − 1) is a position that usually falls between two samples; lo is the whole part of r.

Say it aloud

p-q equals s of lo, plus r minus lo, times the gap from s of lo to s of lo plus one.

pq
p-q the q-th percentile of the cycle times, in µs.
s[lo]
s of lo the sorted sample just below the rank.
r
r the rank, (q/100) times (n − 1). With n = 20 samples it runs from 0 to 19.
lo
lo the whole-number part of r, read "floor of r".
In plain words

Sort the samples. Find the rank r. Start at the sample below it, s of lo, and walk the fraction r minus lo of the way to the next sample.

With numbers

For p99 on the twenty samples: r = 0.99 × 19 = 18.81, so lo = 18, between s[18] = 1,040 and s[19] = 4,000. p99 = 1,040 + 0.81 × 2,960 = 3,437.6 µs. The same rule gives p50 = 1,013.5 and p99.9 = 3,943.76 µs.

980, 985, 988, 992, 996, 1000, 1004, 1008, 1010, 1012, 1015, 1018, 1020, 1024, 1028, 1030, 1034, 1038, 1040, 4000

The value is flat near 1,040 µs up to p94.7, then jumps once the rank passes 18. That is the rule to carry: a fault that hits a share f of cycles shows only in percentiles above 100(1 − f). One cycle in a thousand needs p99.9. At 1 kHz that fault strikes once a second, 86,400 times a day.

Symptom: the dashboard shows p99 green while the robot trips once a second.

Measure: compare the fault rate with the percentile. One in a thousand at 1 kHz is a p99.9 event; p99 looks at a slice ten times too wide and stays in the healthy cluster.

Fix: plot the percentile with as many nines as the fault rate has zeros, next to the maximum.

A 1 kHz loop stalls on 1 cycle in 1,000. Over a long run, which statistic lands on the stall?

Chapter 3

How Long to Look: Rare Faults and Test Length

Compute the chance that a bench run never meets the fault

The CI bench runs the arm loop for 60 seconds and reports a clean maximum. The field units miss deadlines anyway. Who is right? Both. The bench was too short to meet the fault.

A soak is a long run that logs every cycle. Suppose a stall happens once in a million cycles. A 60 s run at 1 kHz logs 60,000 cycles. How likely is it to see the stall even once?

Run a hundred benches

Each square is one bench run of the length you choose. It turns red if it caught the fault at least once. Right: the chance to catch it against run length. Pick a fault rate and drag the length.

60 s

Exact probabilities. Which squares turn red is a fixed random draw, so a square stays red as the run grows. The loop runs at 1 kHz.

Call the fault rate per cycle f and the number of logged cycles N. Each cycle misses the fault with chance 1 − f, and the cycles are independent.

Say it aloud

P-none equals one minus f, to the power N, which is about e to the minus N f.

Pnone
P-none the chance that a run of N cycles never shows the fault.
f
f the fault rate: the chance that one cycle has the fault.
N
N the number of cycles in the run: seconds times 1,000 at 1 kHz.
e−N f
e to the minus N f the short form for small f. N times f is the number of faults you expect to see.
In plain words

Multiply the chance of a clean cycle, 1 minus f, once for each of the N cycles. When f is small, that is e to the minus the expected count N f.

With numbers

f = 10−6, a 60 s bench: N = 60,000 and N f = 0.06. P-none = e−0.06 = 0.942. So 94 benches in 100 pass a loop that is broken. A 2.8 hour soak has N = 107: about 10 faults expected, and P-none is 0.000045.

The same arithmetic limits deep percentiles. In a 1,000-cycle log, the p99.9 rests on one sample. For a 1-in-1,000 fault, that log holds no fault cycle at all 37% of the time. Report each percentile with its sample count: "p99.9 = 4.0 ms, 107 cycles".

Symptom: the bench says the worst cycle is 1.04 ms; the field sees 4 ms stalls.

Measure: compute N f for the fault rate you must rule out. Below 1, the bench has not looked.

Fix: soak until N f is at least 10, under the real load. For a 1-in-a-million fault at 1 kHz that is about 2.8 hours.

A fault hits 1 cycle in a million. A 1 kHz bench runs for 60 s and sees no fault. What does that show?

Chapter 4

The Delta-t Inside the Code

Follow one late cycle into a velocity estimate and a torque

Why not run the controller as fast as the CPU allows? Because an engineer designs a discrete controller for one sample interval Δt (delta-t), and its gains assume it. Change Δt and you have a different controller.

The plainest case is the speed estimate. The loop reads the joint angle each cycle and divides the change by the interval. Most code divides by the nominal 1 ms, a constant, not by the time that passed.

Stretch one interval

Top: the pink true joint angle and the blue samples the loop takes. A stall (warm) stretches one interval. Bottom: the purple speed estimate per cycle. Drag the interval, then switch what the code divides by.

4.0 ms

Illustrative joint turning at a steady 1 rad/s, sampled every 1 ms. The yellow line is the made-up trip limit of 2 rad/s.

Call the angle change between two samples Δθ (delta-theta), the interval the code assumes Δtnom, and the interval that passed Δttrue.

Say it aloud

v-hat equals delta-theta over delta-t-nom. So v-hat over v equals delta-t-true over delta-t-nom.

v̂
v-hat the speed the code computes, in rad/s.
Δθ
delta-theta the angle change between two samples, in radians.
Δtnom
delta-t-nom the interval written into the code: 1 ms.
v
v the true speed: delta-theta over delta-t-true.
Δttrue
delta-t-true the time that passed between the two samples.
In plain words

Both speeds share the same angle change delta-theta. So the estimate is wrong by exactly the ratio of the true interval to the assumed one. A cycle that is four times long gives a speed four times too big.

With numbers

The joint moves 0.004 rad during a stretched 4 ms interval. The code computes 0.004/0.001 = 4.0 rad/s. The truth is 0.004/0.004 = 1.0 rad/s. With a damping gain of 0.5 N·m·s/rad, the brake command is 2.0 N·m where 0.5 was right.

A milder stall does milder damage: a cycle 30% late gives a speed 30% too big, and a torque 30% too big. The error tracks the timing error one for one.

Symptom: the controller is smooth on the bench and jerky in the field, on the same code.

Measure: histogram the real interval between loop starts, and plot the control error against it. Error spikes sit on the long intervals.

Fix: run the loop on a periodic real-time thread, and divide by the measured interval from the timestamps.

A cycle runs 1.3 ms instead of 1 ms, and the code divides by 1 ms. The joint truly moved at 100 rad/s. What does the code compute?

Chapter 5

Same Mean Rate, Opposite Fate

Run one controller at a fixed and a jittered interval, and see why the jittered one grows

Chapter 4 was one bad cycle. Now let every interval wobble around 20 ms, with the mean still 20 ms. The controller sits at the edge of stability for 20 ms. Does a wobble average out?

It does not. Each step multiplies the state by a factor that depends on that step's Δt. Short steps shrink the state and long steps grow it. Long steps grow it more than short steps shrink it.

Jitter the interval, keep the mean

Left: the size of the error, on a log scale, for the fixed run (teal) and the jittered run (warm). Right: the log of the growth per step against Δt; the warm chord joins a short and a long step. Drag the jitter.

±40%

Illustrative PD controller on a unit mass, kp = 2000, kd = 40, explicit Euler steps. The intervals come evenly from the jitter band, with a fixed seed. Same model as the Code Lab below.

For this controller, one step multiplies the area of the state's spread by an amount set by Δt. Call it the growth per step ρ (rho). Call the gains on position and speed kp and kd.

Say it aloud

Rho of delta-t equals one, minus k-d times delta-t, plus k-p times delta-t squared.

ρ(Δt)
rho of delta-t how much one step grows the area of the state (position, speed). Above 1 grows, below 1 shrinks. It is the determinant of the one-step matrix.
kd
k-d the speed gain: 40 per second here.
Δt
delta-t the length of this step, in seconds.
kp
k-p the position gain: 2000 per second squared here.
In plain words

Over many steps, the areas multiply. So what matters is the average of the log of rho, not rho at the average delta-t. The log of rho curves upward here, so a short and a long step average to more growth than two mean steps.

With numbers

At Δt = 0.020 s, ρ = 1 − 0.8 + 0.8 = 1.000: the edge. Alternate 12 ms and 28 ms (mean 20 ms): ρ = 0.808 and 1.448. Their product is 1.170 per pair, so the area grows 17% every two steps.

That is Jensen's inequality: for a curve that bends upward, the average of the curve is above the curve at the average. With ±40% uniform jitter, the average log growth is +0.026 per step: the area grows about 13 times every 100 steps. The Code Lab runs the same model.

Symptom: a loop that looks on rate, mean 20.0 ms, oscillates and grows in the field.

Measure: histogram the step intervals, not their mean. A wide band means the controller you run is not the one you designed.

Fix: fix the rate with a periodic real-time thread, or design the gains for the worst Δt in the band and leave margin from the edge.

Two runs of one controller have the same mean interval. The fixed run is stable; the jittered run diverges. Why?

Chapter 6

Will It Fit? Utilisation and Response Time

Check a task set with one bound, then find the worst case exactly

Three periodic tasks share one core. A safety monitor needs 120 µs every 500 µs. The torque loop needs 350 µs every 1,000. A logger needs 800 µs every 8,000. Under rate-monotonic priority, the shorter period always wins: monitor, then torque, then logger. Will every deadline hold?

Schedule three tasks

All three tasks start together at time 0, the worst moment. Each row is a task; warm blocks interfere with the teal torque loop. Drag the torque loop's compute, then let the logger hold a lock.

350 µs

Exact fixed-priority preemptive schedule, 1 µs steps, deadlines equal to periods, no context-switch cost. Illustrative task times.

First a fast screen. Call each task's worst-case compute Ci and its period Ti; n is the number of tasks. Liu and Layland proved this bound in 1973.

Say it aloud

U equals the sum over i of C-i over T-i, and it must be at most n times the quantity two to the one over n, minus one.

U
U the utilisation: the share of the CPU the tasks need.
Σi
the sum over i add one term for each task.
Ci
C-i task i's worst-case compute time, in µs.
Ti
T-i task i's period, which is also its deadline here.
n (21/n − 1)
the rate-monotonic bound 1 for one task, 0.828 for two, 0.780 for three, falling toward 0.693.
In plain words

Divide each task's compute C-i by its period T-i, and add the shares. If the total U is under the bound for n tasks, every deadline holds under rate-monotonic priority. If not, the test says nothing either way.

With numbers

U = 120/500 + 350/1000 + 800/8000 = 0.24 + 0.35 + 0.10 = 0.69. The bound for n = 3 is 3 × (1.2599 − 1) = 0.780. 0.69 is under it: guaranteed.

The bound assumes the tasks never block each other. To see one task's real worst case, compute its response time R: its compute, plus B, the longest time a lower task can block it, plus every run of a higher task j that fits inside R.

Say it aloud

R equals C plus B plus the sum over j of the ceiling of R over T-j, times C-j.

R
R the worst-case response time: release to finish. It must be at most the deadline.
C
C this task's own compute.
B
B the blocking: the longest stretch a lower task can hold the CPU or a lock this task needs.
Σj
the sum over j one term for each task with higher priority.
⌈R / Tj⌉
the ceiling of R over T-j how many times task j is released inside R, rounded up.
Cj
C-j the compute of each release of task j.
In plain words

R appears on both sides, so iterate. Start with R = C + B. Count the higher releases that fit in R, add their compute, and repeat until R stops changing.

With numbers

Torque loop, B = 0: start at 350; one monitor release fits, so R = 350 + 120 = 470, and it stays. Deadline 1,000: 530 µs of slack. If the logger holds an 800 µs lock: 1,150, then 1,510, then 1,630, then 1,630. That is 630 µs late, with U still 0.69.

Symptom: a high-priority loop misses while the CPU is 69% busy.

Measure: trace lock hold times. A miss that lines up with a low task holding a shared lock is priority inversion.

Fix: keep critical sections short, use priority inheritance on the lock, and budget B. Here B ≤ 410 µs keeps R ≤ 1,000.

U = 0.69, under the bound of 0.78, yet the torque loop misses. What is the likely cause?

Chapter 7

The Whole Track as One Latency Budget

Chain every stage of Lessons 1 to 9, and decide which ones the motor may wait for

Every earlier lesson is a stage in one pipeline, and every stage spends time. The camera exposes, and the driver stamps the capture time (Lesson 2). The tf tree gives the camera's pose at that time (Lesson 1).

The frontend matches features (Lesson 6). The estimator fuses the sensors with their noise (Lesson 3, Lesson 4). The map and detections update (Lesson 9). Then the planner runs, then this lesson's 1 kHz loop.

Age is a cost the earlier lessons measured. In Lesson 2, a scan stamped 12 ms late at 3.4 m/s put each point 40.8 mm off. In Lesson 9, a scan placed 30 ms late during a 90°/s turn put a wall 5 m away 24 cm off.

Chain the track

Top: one frame's trip from camera to motor, each stage a block with its lesson number. Below: the backend and loop closure run beside it. Drag how often each stage is slow, then choose how the control loop takes its input.

1.0%

Illustrative stage times in milliseconds; a slow stage takes three times its typical time. We assume the stages are independent. The age numbers come from Lessons 2 and 9.

Suppose each of k stages is slow on a share p of frames, independently. A frame is late if any stage is slow.

Say it aloud

P-slow equals one minus the quantity one minus p, to the power k.

Pslow
P-slow the share of frames that meet at least one slow stage.
p
p the chance that one stage is slow on one frame.
k
k the number of stages the frame waits for in a row.
In plain words

A frame is on time only if all k stages are fast. Multiply the chance of fast, 1 minus p, once per stage. Take that from 1.

With numbers

With made-up numbers, k = 7 and p = 0.01: 1 − 0.997 = 0.068. Each stage is slow 1% of the time; the chain is slow on 6.8% of frames. Dean and Barroso's example: one request to 100 servers, each slow 1% of the time, is slow 63% of the time.

The 1 kHz loop must never wait for a 30 Hz frame. Each handoff writes the newest stamped result into a slot, and the next stage reads it without waiting. A slow frame then costs age, not a missed tick. The backend of Lesson 7 and the loop closures of Lesson 8 run beside the chain. Their corrections arrive late on purpose, through map to odom, never as a jump in the controller's frame.

Symptom: each stage meets its own p99, yet one frame in fifteen arrives late.

Measure: log each frame's age, from its capture stamp, at every stage. Budget the end-to-end age.

Fix: cut the blocking chain into latest-value handoffs, drop stale frames (firm), and keep only the control loop on a hard deadline.

A 1 kHz controller needs the pose from a 30 Hz visual pipeline. How should it read it?

Chapter 8

Find the Culprit: What to Log and How to Read It

Turn a list of trip times into the period of the task that caused them

Back to the arm. You cannot reproduce the trip, but you have a log with the time of each one. The raw times look like large random numbers. Subtract each from the next.

A random hardware glitch gives gaps with no pattern. A periodic task gives the same gap every time, give or take its jitter. That gap is the task's period. Look it up in the process list.

Difference the trip times

Top: each red tick is a logged trip. Bottom: each blue dot is the gap between two trips, and the purple line marks the most common gap. Set the culprit's period and jitter, then add random glitches.

1000 ms
15 ms

Illustrative log of 24 trips. Jitter is spread evenly within ± the value; glitches are extra trips at random times. The marker is the mean of the gaps in the fullest cluster.

Worked number. Trips logged at 2,004.5, 2,995.9, 3,986.7 and 4,993.2 ms give gaps of 991.4, 990.8 and 1,006.5 ms. Around 1,000 ms each time: a once-a-second task. The logger flushes once a second.

What to log on any real-time robot, from this lesson:

Log thisIt catchesRead it as
Max and p99.9 cycle time, with the cycle counta rare stallagainst the deadline (Ch 2, 3)
Histogram of the interval between loop startsjitter, a wrong Δtwidth of the band (Ch 4, 5)
Time of each trip or missa periodic culpritgaps between them (this chapter)
Lock hold times by taskpriority inversionoverlap with the miss (Ch 6)
Capture stamp and age at each stagea blocking chainend-to-end age (Ch 7)
Deadline-miss counter and watchdogany miss at alla hard loop goes to a safe state on one miss

On Linux, cyclictest measures how late the kernel wakes a periodic thread, and ftrace shows which task held the CPU. The PREEMPT_RT patches that bound that wake-up delay entered the mainline kernel in version 6.12, in 2024.

Symptom: a fault "has no pattern", so the team blames hardware.

Measure: difference the fault times and histogram the gaps.

Fix: a cluster names a period; find the task with it. No cluster after hundreds of faults is evidence for hardware.

Trip gaps read 2,003, 1,996, 2,010, 1,991 and 2,001 ms. What do you look for?

Chapter 9

Showcase: Jitter a Live Loop Until It Misses

Drive a loop from healthy to failing and see which number moves first

Everything in one instrument. Each control cycle is a dot at its loop time, the time from release to finish. The yellow line is the 1,000 µs deadline. A histogram of the last 2,000 cycles carries the mean, p50, p99 and p99.9.

Two knobs. Jitter spreads each cycle both ways around its typical 700 µs. Preemption adds a one-sided stall of 1,800 to 3,300 µs to a share of cycles.

Drive the loop to failure

Left: the last 60 cycles, blue on time and red past the deadline. Right: the histogram of the last 2,000, bar heights on a square-root scale so the thin tail shows. Raise preemption and watch which purple marker moves first.

15%
0.8%

Illustrative loop: typical work 700 µs, jitter up to ±0.4 × 700 µs at 100%, stall 1,800 to 3,300 µs. Seeded random draws, about 60 cycles a second on screen.

Worked number. At 0.8% preemption, a full window holds about 16 stalls among 1,984 healthy cycles. With 3,200 µs stalls and 700 µs cycles, the mean is (1,984 × 700 + 16 × 3,200)/2,000 = 720 µs, under the deadline. The p99.9 rank, 0.999 × 1,999 = 1,997, lands inside the stalls: 3,200 µs, 3.2 times the period.

Jitter alone cannot miss here. At 100% jitter the widest cycle is 700 + 280 = 980 µs. Every red dot is a preemption. At 0.1% preemption only about 2 stalls sit in the window, and p99.9 falls back to 702.5 µs; p99.99 still reads 3,200.

Symptom: the mean marker stays green while red dots keep appearing.

Measure: read the p99.9 marker and the miss count over the same window.

Fix: remove the source of the stall (Ch 6), not the jitter: here jitter never crosses the line.

Preemption is 0 and jitter is 100%. With typical work 700 µs and jitter up to 0.4 × 700, will any cycle miss the 1,000 µs deadline?

Chapter 10

Field Guide

Keep the numbers, the code and the whole track in one place

Real-time means predictable. Price a miss with the deadline's value function. Read the tail with a percentile that has as many nines as the fault rate has zeros, from a soak long enough to meet the fault. Hold Δt fixed, or measure it, because a controller's gains assume it and jitter adds up. Screen a task set with the rate-monotonic bound, then prove the hard loop with its response time, blocking included. Let the motor wait for nothing slower than itself.

QuestionNumber to quoteThis lesson's example
What does a miss cost?E[V] = 1 − p(1 − vlate)firm 0.98, soft 0.995 at p = 2%
Where is the fault?p100(1−f) and the max1 in 1,000 needs p99.9
Did the test look?N f, with Pnone = e−N f60 s bench: 0.06; 94% miss it
What does a late cycle do?Δttrue/Δtnom4 ms cycle: speed 4 times too big
Is jitter safe?average of log ρ(Δt)±40%: +0.026 per step, diverges
Does the set fit?U against n(21/n − 1)0.69 ≤ 0.780
Does the hard loop hold?R against D470 µs; 1,630 with an 800 µs lock
How late is the frame?1 − (1 − p)k and the age7 stages at 1%: 6.8%
python
import math
import numpy as np

def percentile(times, q):
    """Rank r = (q/100)(n-1), then walk between the two neighbours (NumPy's default)."""
    s = np.sort(np.asarray(times, float))
    r = q / 100 * (len(s) - 1)
    lo = int(math.floor(r)); hi = min(lo + 1, len(s) - 1)
    return s[lo] + (r - lo) * (s[hi] - s[lo])

def p_none(f, n_cycles):
    """Chance a run of n_cycles never shows a fault of rate f per cycle."""
    return (1 - f) ** n_cycles

def rm_bound(tasks):
    """tasks: [(C, T)]. Liu and Layland screen: True means guaranteed."""
    U = sum(C / T for C, T in tasks); n = len(tasks)
    return U, n * (2 ** (1 / n) - 1), U <= n * (2 ** (1 / n) - 1)

def response_time(C, higher, B=0, limit=10**7):
    """R = C + B + sum(ceil(R/Tj) Cj) over higher-priority (Cj, Tj); iterate to a fixed point."""
    R = C + B
    while R <= limit:
        R_next = C + B + sum(math.ceil(R / Tj) * Cj for Cj, Tj in higher)
        if R_next == R:
            return R
        R = R_next
    return math.inf

def chain_slow(p, k):
    """Share of frames that meet at least one slow stage among k independent stages."""
    return 1 - (1 - p) ** k

s20 = [980, 985, 988, 992, 996, 1000, 1004, 1008, 1010, 1012,
       1015, 1018, 1020, 1024, 1028, 1030, 1034, 1038, 1040, 4000]
print(percentile(s20, 99))                                    # 3437.6
print(p_none(1e-6, 60_000))                                    # 0.942
print(rm_bound([(120, 500), (350, 1000), (800, 8000)]))        # (0.69, 0.7798, True)
print(response_time(350, [(120, 500)]), response_time(350, [(120, 500)], B=800))  # 470 1630
print(chain_slow(0.01, 7))                                      # 0.068

We ran each function: the comments are its output, and they match the chapters. percentile agrees with numpy.percentile on every example here.

Where it sits. ROS 2's documentation says its standard executors are not built for hard real-time: callbacks can suffer priority inversion and there is no explicit control of their order. It suggests running the control loop's callbacks on their own executor thread with a higher operating-system priority. Many robots go further and run the innermost torque loop on a microcontroller or a dedicated core.

The track, lesson by lesson, in time

LessonIts numberIts place in the time budget
1, Frames4.14 cm miss at 30°every tf lookup asks for a pose at a time
2, Time and Sync12 ms stamp error, 40.8 mmthe capture stamp that every age starts from
3, Uncertainty45 cm off from one bad matcha robust solve has a cost per frame
4, Sensors9 cm fused, 40 cm without radareach sensor arrives at its own rate
5, Calibration23 mm typed for 25: depths 8% shortthe time offset between sensors is a calibration too
6, SLAM Frontendone false closure bends the map 7.6 mthe 30 Hz tracking path
7, SLAM Backendthe solve time you can predictbeside the chain, never in the 1 kHz loop
8, Drift and Loop Closure0.85 m drift, 3 cm after a closurecorrections arrive late, through map to odom
9, Downstream Perception30 ms late: a wall 24 cm offbuild the map at the right pose and time
10, this lessonone 4 ms cycle in 1,000the deadline the whole chain feeds

Keep going

Read next

The habit. For every number on the dashboard, ask which cycle it describes. If the answer is "none of them", it is an average; find the tail and hold it against the deadline.
Which sentence carries this lesson?

Now teach it: press Present or Teach and explain why the arm trips while the mean reads 1.003 ms. Then go back to the arm loop and find the largest stall the arm survives, before you drag.

The Real-Time Mental Model · Robotics Engineering, Lesson 10
Previous: Downstream Perception · Back to Lesson 1 · Back to Gleams