---
title: Latency, jitter and deadlines
heading: Doing things on time, every time
eyebrow: C12 · Lesson 39 · Latency, jitter and deadlines
xp: 40
---

::: hook
"Real time" doesn't mean fast. It means **on time**: a motor controller that updates every millisecond, give or take a microsecond, is real-time; one that's usually quicker but sometimes a millisecond late is not. Three numbers describe it. **Latency** is how long a response takes to start after its trigger. **Jitter** is how much that time varies. A **deadline** is the latest a job may finish and still be correct. Designing for real time means knowing the worst case of each, not the average.
:::

::: play
- A control task must run every 1 ms; each run toggles P0 and records the gap since the last run. Meanwhile, background work runs in chunks of 0 to 0.8 ms. After 200 runs the program prints the jitter: the longest gap minus the shortest, in microseconds.
- Polled from the loop (`USE_IRQ 0`), the task runs whenever the background chunk ends: it prints about 1215 µs. Zoom in on P0 and see the uneven edges.
- With `USE_IRQ 1` the timer interrupt runs it the instant the period is up, whatever the loop is doing: it prints 0. (On a real chip, a cycle or two.)
:::
:::

```sim board
lang: c
scope: P0 | 0..20 ms
run: 0.25 s
code:
#include "board.h"

#define USE_IRQ 0

volatile uint32_t last = 0, min_gap = 0xFFFFFFFF, max_gap = 0, runs = 0;

void control(void) {                     // the job that must run every 1 ms
    uint32_t now = SYS_CYCLES;
    GPIO_TOGGLE = 1;
    if (runs) {
        uint32_t gap = now - last;
        if (gap < min_gap) min_gap = gap;
        if (gap > max_gap) max_gap = gap;
    }
    last = now;
    runs++;
}

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    control();
}

uint32_t lfsr = 0xACE1;
void background(void) {                  // other work, 0 to 0.8 ms at a time
    lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & 0xB400);
    uint32_t t = SYS_CYCLES, len = (lfsr & 0xFF) * 31;
    while (SYS_CYCLES - t < len) ;
}

int main(void) {
    GPIO_DIR = 1;
    TIMER_PRESCALE = 0;
    TIMER_TOP = 9999;                    // every 1 ms
    if (USE_IRQ) {
        set_trap_handler(on_timer);
        TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
        enable_external_interrupt();
        enable_interrupts();
    } else {
        TIMER_CTRL = TIMER_RUN;
    }
    while (runs < 200) {
        if (!USE_IRQ && (TIMER_FLAGS & 1)) {   // polled: run it when we get round to it
            TIMER_FLAGS = 1;
            control();
        }
        background();
    }
    print((max_gap - min_gap) / 10);     // the jitter, in microseconds
    return 0;
}
```

::: predict
## A superloop checks a flag once per pass, and a pass takes anywhere from 0.1 ms to 0.9 ms. What's the worst-case latency for responding to the flag?

- [ ] 0.1 ms
- [ ] 0.5 ms
- [x] About 0.9 ms
- [ ] 1.8 ms

::: reveal
About 0.9 ms: the flag can be set just after the check, and then it waits a whole pass, which can be the longest one. Average latency is half a pass, but real-time design uses the worst case, because the one late response is the one that breaks things.
:::
:::

::: nameit
## The three numbers

- **Latency:** from the trigger (an edge, a timer, a byte) to the start of the response.
- **Jitter:** the spread in latency, or in the interval between periodic events: maximum minus minimum.
- **Deadline:** the latest a job may finish. A job meets it if, in the worst case, latency plus execution time ($C$, its worst-case execution time) fits: $L_\text{max} + C \le D$.

**Hard** real time means a missed deadline is a failure (an airbag, a motor commutation); **soft** real time means lateness only degrades quality (an audio glitch, a sluggish display).

## Where jitter comes from

- polling: the response waits for the loop to come round;
- other tasks' turns in a cooperative scheduler;
- sections with interrupts disabled, and other interrupts' handlers;
- code whose running time varies with its data.

The cures, roughly in order: move the job to an interrupt; keep ISRs and critical sections short; give urgent sources higher priority; and for the strictest timing, let hardware act directly (a timer driving a PWM pin, a DAC fed by DMA) so software isn't in the path at all.

## Why it matters

A sampled control loop or a signal converter assumes evenly spaced samples. Sampling a signal of frequency f and amplitude A at a time off by Δt reads it wrong by up to $2\pi f A\,\Delta t$, the same jitter limit as an ADC's clock (C11).

## Measuring

Toggle a spare pin at the start and end of the job and look at it on a logic analyzer, as the play does: the edges show latency and execution time directly, and their spread over many runs shows the jitter.
:::

::: example
## A 50 Hz signal of amplitude 1 V is sampled with 30 µs of timing jitter. How large can the error in a sample be?

::: solution
1. **Steepest slope times the jitter.**
   $$\begin{aligned} \Delta v &= 2\pi f A\,\Delta t \\ &= 2\pi \times 50 \times 1 \times 30 \times 10^{-6}\ \text{V} \\ &= 9.4\ \text{mV} \end{aligned}$$
2. **Compare with the amplitude.** That's about 1% of the amplitude: comparable to a 7-bit converter's resolution, wasting a 12-bit ADC.

**Answer:** up to 9.4 mV, about 1% of the amplitude.
:::
:::

::: example
## A job must finish within 200 µs of its trigger. It takes up to 120 µs to run, and interrupts may be disabled for up to 50 µs elsewhere. Does it meet its deadline?

::: solution
1. **Wait.** In the worst case the job waits 50 µs, plus the interrupt's few cycles.
2. **Run.** Then it runs for 120 µs:
   $$50 + 120 = 170\ \mu\text{s}$$
   about 170 µs in all, within 200 µs.
3. **Another interrupt first.** If another, higher-priority interrupt can also take 40 µs first, it becomes 210 µs, and it doesn't.

**Answer:** yes, at about 170 µs in the worst case; if a higher-priority interrupt can take 40 µs first, it becomes 210 µs and misses.
:::
:::

::: example
## Three periodic tasks use 25% of the processor in all. Does the rate-monotonic utilization bound guarantee they meet their deadlines?

::: solution
1. **The Liu and Layland bound.** For three tasks it is
   $$3(2^{1/3} - 1) = 0.780$$
2. **Compare.** 25% is well under 78%, so with rate-monotonic priorities (shorter period, higher priority) every deadline is met.
3. **Above the bound.** A more exact response-time analysis is needed.

**Answer:** yes: 25% is well under the three-task bound of 78%.
:::
:::

::: check
given: lo = 0.05 | 0.1 | 0.2; hi = 0.6 | 0.9 | 2
answer: hi
unit: ms
tolerance: 0.5%

## A loop polls a flag once per pass; passes take between {lo} and {hi} ms. What's the worst-case latency?

::: right
Right. {answer} ms: one whole longest pass.
:::

::: misses
- [(lo + hi)/2] That's a typical case; real-time design uses the worst.
- [lo] That's the best case.
- [any] Not yet. The flag can just miss a check and wait the longest pass.
:::
:::

::: check
given: a = 980 | 995 | 999.5; b = 1010 | 1004 | 1001
answer: b - a
unit: µs
tolerance: 0.5%

## A periodic job's measured intervals range from {a} µs to {b} µs. What's its jitter?

::: right
Right. {answer} µs.
:::

::: misses
- [any] Not yet. Longest minus shortest.
:::
:::

::: check
given: L = 10 | 40 | 80; C = 50 | 150; D = 100 | 200
answer: D - L - C
unit: µs
tolerance: 0

## A job's worst-case latency is {L} µs, its worst-case execution time {C} µs, and its deadline {D} µs. How much margin is left (negative if it misses)?

::: right
Right. {answer} µs.
:::

::: misses
- [any] Not yet. Deadline minus latency minus execution time.
:::
:::

::: check
given: f = 50 | 1000 | 10000; A = 1 | 2; dt = 1 | 10 | 100
answer: 2*pi*f*A*dt*1e-6*1000
unit: mV
tolerance: 0.5%

## A {f} Hz signal of amplitude {A} V is sampled with {dt} µs of timing jitter. How large can a sample's error be?

::: right
Right. $2\pi f A\,\Delta t$ = {answer} mV.
:::

::: misses
- [f*A*dt*1e-6*1000] The signal's steepest slope is $2\pi f A$.
- [any] Not yet. Slope times timing error.
:::
:::

::: check
given: C = 20 | 60 | 300; T = 100 | 1000
answer: 100*C/T
unit: %
tolerance: 0.5%

## An ISR runs every {T} µs and takes {C} µs. What share of the time does it occupy, and so how long can it hold off everything below it?

::: right
Right. {answer}% of the time, and it delays lower-priority work by up to {C} µs each period.
:::

::: misses
- [any] Not yet. C over T.
:::
:::

::: check
kind: choice

## A PWM output for a motor must switch at exactly 20 kHz, with no jitter. What's the best way?

- [ ] Toggle a pin from the superloop
- [ ] Toggle a pin from a 40 kHz timer interrupt
- [x] Use the PWM peripheral, which switches the pin in hardware
- [ ] Toggle a pin with a carefully counted delay loop

::: misses
- [1] The loop's pass time varies: that's jitter.
- [2] Better, but other interrupts and disabled sections still add jitter.
- [4] Any interrupt or code change shifts it.
:::
:::

::: check
kind: c
attach: led P0
run: 0.25
expect: print = 0; period(P0) = 2 ms ± 0.1%

## Make the play's control task jitter-free: run it from the timer interrupt instead of polling (everything else stays the same).

```c starter
#include "board.h"

#define USE_IRQ 0

volatile uint32_t last = 0, min_gap = 0xFFFFFFFF, max_gap = 0, runs = 0;

void control(void) {                     // the job that must run every 1 ms
    uint32_t now = SYS_CYCLES;
    GPIO_TOGGLE = 1;
    if (runs) {
        uint32_t gap = now - last;
        if (gap < min_gap) min_gap = gap;
        if (gap > max_gap) max_gap = gap;
    }
    last = now;
    runs++;
}

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    control();
}

uint32_t lfsr = 0xACE1;
void background(void) {                  // other work, 0 to 0.8 ms at a time
    lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & 0xB400);
    uint32_t t = SYS_CYCLES, len = (lfsr & 0xFF) * 31;
    while (SYS_CYCLES - t < len) ;
}

int main(void) {
    GPIO_DIR = 1;
    TIMER_PRESCALE = 0;
    TIMER_TOP = 9999;                    // every 1 ms
    if (USE_IRQ) {
        set_trap_handler(on_timer);
        TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
        enable_external_interrupt();
        enable_interrupts();
    } else {
        TIMER_CTRL = TIMER_RUN;
    }
    while (runs < 200) {
        if (!USE_IRQ && (TIMER_FLAGS & 1)) {   // polled: run it when we get round to it
            TIMER_FLAGS = 1;
            control();
        }
        background();
    }
    print((max_gap - min_gap) / 10);     // the jitter, in microseconds
    return 0;
}
```

```c solution
#include "board.h"

#define USE_IRQ 1

volatile uint32_t last = 0, min_gap = 0xFFFFFFFF, max_gap = 0, runs = 0;

void control(void) {                     // the job that must run every 1 ms
    uint32_t now = SYS_CYCLES;
    GPIO_TOGGLE = 1;
    if (runs) {
        uint32_t gap = now - last;
        if (gap < min_gap) min_gap = gap;
        if (gap > max_gap) max_gap = gap;
    }
    last = now;
    runs++;
}

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    control();
}

uint32_t lfsr = 0xACE1;
void background(void) {                  // other work, 0 to 0.8 ms at a time
    lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & 0xB400);
    uint32_t t = SYS_CYCLES, len = (lfsr & 0xFF) * 31;
    while (SYS_CYCLES - t < len) ;
}

int main(void) {
    GPIO_DIR = 1;
    TIMER_PRESCALE = 0;
    TIMER_TOP = 9999;                    // every 1 ms
    if (USE_IRQ) {
        set_trap_handler(on_timer);
        TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
        enable_external_interrupt();
        enable_interrupts();
    } else {
        TIMER_CTRL = TIMER_RUN;
    }
    while (runs < 200) {
        if (!USE_IRQ && (TIMER_FLAGS & 1)) {   // polled: run it when we get round to it
            TIMER_FLAGS = 1;
            control();
        }
        background();
    }
    print((max_gap - min_gap) / 10);     // the jitter, in microseconds
    return 0;
}
```

::: right
Right. The interrupt starts the task at the same point after each timer wrap, whatever the background is doing.
:::
:::

::: check
kind: micropython
attach: led P0
run: 1
expect: period(P0) = 20 ms ± 1%

## Toggle P0 every 10 ms, steadily, while the main loop does work of varying length (the starter's `work`). Use a `machine.Timer`.

```micropython starter
from machine import Pin, Timer
import time

led = Pin(0, Pin.OUT)
sensor = Pin(4, Pin.IN, Pin.PULL_UP)
n = 1
def work():
    global n
    n = (n * 7 + 3) % 50
    for i in range(n):
        sensor.value()

while True:
    led.toggle()
    work()
    time.sleep_ms(10)
```

```micropython solution
from machine import Pin, Timer
import time

led = Pin(0, Pin.OUT)
sensor = Pin(4, Pin.IN, Pin.PULL_UP)
n = 1
def work():
    global n
    n = (n * 7 + 3) % 50
    for i in range(n):
        sensor.value()

Timer(period=10, mode=Timer.PERIODIC, callback=lambda t: led.toggle())
while True:
    work()
    time.sleep_ms(1)
```

::: right
Right. The timer's callback runs within one hardware call of its due time, however long `work` takes.
:::
:::

::: check
kind: parts
given: f = 50 | 1000; A = 1 | 1.65; j = 1 | 10 | 30

## A {f} Hz sine of amplitude {A} V is sampled with {j} µs of timing jitter.

::: part
answer: 2*pi*f*A*j*1e-6*1000
unit: mV
tolerance: 0.5%

### How large can the error be, at most?

::: misses
- [any] $2\pi fA\Delta t$, the steepest slope times the jitter.
:::
:::

::: part
answer: 2*pi*f*A*j*1e-6*1000/(3.3/4095*1000)
tolerance: 0.5%

### How many 12-bit ADC codes (0.806 mV each) is that?

::: misses
- [any] Error ÷ one code.
:::
:::
:::

::: check
kind: parts
given: n = 2 | 3 | 4 | 8

## {n} periodic tasks are scheduled rate-monotonically.

::: part
answer: n*(2^(1/n) - 1)*100
unit: %
tolerance: 0.5%

### What is the Liu and Layland utilization bound?

::: misses
- [any] $n(2^{1/n} - 1)$.
:::
:::

::: part
answer: ln(2)*100
unit: %
tolerance: 0.5%

### What does it approach for many tasks?

::: misses
- [any] ln 2.
:::
:::
:::

::: explain
## Why do real-time designs care about the worst case instead of the average?

::: model
A real-time requirement is a promise about every occurrence: every control update on time, every byte read before the next arrives, every airbag fired within its window. The average can look comfortable while the rare worst case, when several slow things line up (a long background chunk, an interrupt, a disabled section), misses the deadline, and one miss can mean a crash, a lost byte or an unstable control loop. So designers bound each delay's worst case, add them up, and check the sum against the deadline, then measure, looking for the longest latency seen over many runs rather than the typical one.
:::
:::

::: practice

::: check
given: lo = 0.2 | 0.4; hi = 1.5 | 3
answer: hi
unit: ms
tolerance: 0.5%

## Worst-case polling latency with passes of {lo} to {hi} ms?

::: misses
- [any] The longest pass.
:::
:::

::: check
given: L = 25 | 60; C = 80 | 130; D = 150 | 250
answer: D - L - C
unit: µs
tolerance: 0

## Margin: latency {L}, execution {C}, deadline {D} µs?

::: misses
- [any] D − L − C.
:::
:::

::: check
given: f = 400 | 5000; A = 1.5; dt = 2 | 20
answer: 2*pi*f*A*dt*1e-6*1000
unit: mV
tolerance: 0.5%

## Error from {dt} µs jitter on {A} V at {f} Hz?

::: misses
- [any] $2\pi f A\,\Delta t$.
:::
:::
:::
