Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F407, STM32G031 · level intermediate · 10 min read
Open in the interactive handbook

76в. Sorting networks: median of 3, 5 and 9 without branches and constant time on Cortex-M

In 76б sorts were chosen by their worst case. But when the number of elements is always the same small number — 3, 5 or 9 samples of a median filter, a window of 3 × 3 pixels — you can do better: one and the same sequence of actions for any data. The time then does not depend on the input at all, and on a Cortex-M4 not a single conditional branch remains in the machine code.

Basis: alg.c with the medians and networks built with gcc 12.2.0 on the computer (stm-sys:1): each network was checked on all sets of zeros and ones, and the median of nine on all 362880 permutations of nine numbers. The same file built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — that gives the number of instructions and conditional branches in each function. Cycles on silicon were not measured.

Terms used in the documentation

Original Meaning
sorting network sorting network: a fixed chain of compare-and-swap steps
comparator, compare-exchange comparator: a pair "smaller goes here, larger goes there"
network depth network depth: the number of stages if independent comparators run in parallel
zero-one principle the 0-1 principle: a network is correct if it sorts all sets of zeros and ones
branchless code code without branches
data-independent timing time that does not depend on the data
median of medians (pseudo-median) median of medians: an approximate median over groups

In plain words. An ordinary sort decides what to do next by looking at the data: "if greater — swap". A sorting network decides everything in advance: compare the first with the second, then the fourth with the fifth and so on — always the same pairs, in the same order. In each pair the smaller goes left, the larger goes right. It is a little more work, but it is always the same, and the processor does not have to guess where the program will go.


76в.1 What a sorting network is

A network is wires, one per element, and comparators between pairs of wires. A comparator takes two values and outputs them in the order "smaller, larger". The sequence of comparators is fixed once and for all, it does not depend on the data. The figure shows a network for five inputs made of nine comparators:

Five horizontal wires — inputs a, b, c, d, e, with nine vertical comparators between them, numbered in order and laid out in 6 stages; at the output the wires give the elements from the 1st to the 5th in size, the third is highlighted as the median

Comparators that do not share wires can run at the same time — that is how the depth of a network is counted. This network has 9 comparators and 6 stages. On a single-threaded microcontroller the depth matters less than the number of comparators, but it shows how many independent operations the processor pipeline can overlap.

Why this is better than insertion from 76б: with insertion the number of comparisons depends on how sorted the input is, with a network it does not. Why it is worse: a network makes all its comparisons even if the input is already in order, and for large n there are too many comparators. Networks are good on 3–16 elements.


76в.2 A comparator through min and max

A comparator in C is two expressions that are always evaluated:

#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) < (b) ? (b) : (a))
#define CSWAP(x, y) do { int32_t lo_ = MIN(x, y), hi_ = MAX(x, y); x = lo_; y = hi_; } while (0)

The ternary operator looks like a branch, but the compiler for Cortex-M4 turns it into a comparison and a pair of conditional moves in an IT block: one cmp instruction, then it and the moves, which are executed or skipped without a jump. There are no branches — the pipeline is not flushed, and the time is the same for any outcome of the comparison.

The Cortex-M0 has the Thumb-1 instruction set, which has neither it nor conditional moves. The same macros on M0 turn into real branches — this is visible in the table in 76в.6. The network on M0 still performs the same comparisons in the same order, but the time of each comparator slightly depends on whether a branch was taken.

The network values are kept in 32-bit variables even if the samples are 16-bit: the Cortex-M registers are 32-bit, and the compiler does not have to do extra sign extensions.


76в.3 Median of three

The usual way to write it is a tree of conditions:

int32_t med3_if(int32_t a, int32_t b, int32_t c)
{
    if (a > b) {
        if (b > c) return b;
        return a > c ? c : a;
    }
    if (a > c) return a;
    return b > c ? c : b;
}

The same median through min and max — four operations and not a single condition:

int32_t med3_net(int32_t a, int32_t b, int32_t c)
{
    return MAX(MIN(a, b), MIN(MAX(a, b), c));
}

The meaning: the smaller of (a, b) is the lower candidate; the larger of (a, b), clipped from above by the value c, is the upper candidate; the median is the larger of the two candidates. On all 27 sets of the numbers 0, 1, 2 both functions gave the same answer. On M4 med3_if is 18 instructions and 3 conditional branches, med3_net is 16 instructions and none.


76в.4 Median of five and the full network for five

A full sort of five is the nine comparators from the figure:

CSWAP(a, b); CSWAP(d, e); CSWAP(c, e);
CSWAP(c, d); CSWAP(a, d); CSWAP(a, c);
CSWAP(b, e); CSWAP(b, d); CSWAP(b, c);

If only the median is needed, fewer suffice. From the pair (a, b) and the pair (c, d) take "the larger of the smaller" and "the smaller of the larger" — the median of five lies between them or equals the fifth element:

int32_t f = MAX(MIN(a, b), MIN(c, d));
int32_t g = MIN(MAX(a, b), MAX(c, d));
return med3_net(e, f, g);

That is ten min/max operations instead of eighteen in the full network. On M4 med5_net is 39 instructions, sort5_net is 73, and neither has conditional branches.


76в.5 Median of nine: 19 comparators

A 3 × 3 window is the standard for a median filter of an image from an image sensor or a thermal imaging array. Nine elements do not need to be sorted completely: a well-known network of 19 comparators puts the median in fifth place without putting the rest in order:

CSWAP(p1, p2); CSWAP(p4, p5); CSWAP(p7, p8);
CSWAP(p0, p1); CSWAP(p3, p4); CSWAP(p6, p7);
CSWAP(p1, p2); CSWAP(p4, p5); CSWAP(p7, p8);
CSWAP(p0, p3); CSWAP(p5, p8); CSWAP(p4, p7);
CSWAP(p3, p6); CSWAP(p1, p4); CSWAP(p2, p5);
CSWAP(p4, p7); CSWAP(p4, p2); CSWAP(p6, p4);
CSWAP(p4, p2);
return p4;

For comparison — the same median by insertion into a local array (med9_ins). A run over all 362880 permutations of the numbers 0…8:

Method comparisons, fewest most on average
network med9_net 19 19 19
insertion med9_ins 8 36 24.2

Insertion is at best half the cost of the network, at worst almost twice as expensive, and between them is a spread of 4.5 times. The network is always 19.

There is also a cheap substitute — the median of medians: the medians of three triples, then the median of those, four calls of med3_net. This is not the exact median: on 155520 permutations out of 362880, that is in 42.9 % of cases, it was wrong — though always by no more than one rank (it gave the 4th or 6th element instead of the 5th). For suppressing a single outlier that is enough, for an honest median it is not.


76в.6 Machine code: instructions and branches

Build at -O2, the number of instructions in the function and of conditional branches among them:

Function M4: instructions M4: branches M0: instructions M0: branches
med3_if 18 3 18 5
med3_net 16 0 16 4
med5_net 39 0 38 10
sort5_net 73 0 76 18
med9_net 117 0 140 30
med9_ins 30 3 48 4
med9_approx 63 0 72 16

On M4 all networks have zero branches: the function runs from the first instruction to the last, and the number of executed instructions equals the number of instructions in the code — 117 for the median of nine for any data. med9_ins has only 30 instructions, but it is a loop: it runs from 8 to 36 comparisons with moves, and how many exactly depends on the input.

How many cycles this is cannot be said exactly from the instructions alone: on M4 most data-processing instructions take one cycle, loads from memory and branches take longer. The estimate is of the order of the instruction count for a network without branches; the exact number comes only from a measurement with the DWT counter on silicon (73).

On M0 every function has branches: 30 in the median of nine. This number is not a coincidence: on M4 the same function has 30 IT blocks, and each of them on M0 turned into a branch — likewise for med3_net (4 and 4), med5_net (10 and 10) and sort5_net (18 and 18). The network still performs the same comparisons, but the time of each function now floats slightly. If strictly constant time is needed on M0, min and max are written with arithmetic: a mask from the sign of the difference ((a - b) >> 31) and &, | — without branches, at the cost of a few extra instructions and provided that the difference does not overflow (for 16-bit samples in int32_t it does not).


76в.7 How to check that a network is correct

A network of 19 comparators is easy to rewrite with an error: swap the order in one pair or drop a comparator. Some errors show up at once, others appear on rare inputs, and random data are not enough for checking. There is an exact method — the 0-1 principle: if a network correctly sorts all sets of zeros and ones, it correctly sorts any numbers. For five inputs that is 32 sets, for nine — 512. The median of nine on a set of zeros and ones must be one exactly when there are five or more ones.

Both methods were checked on the bench: all 32 and all 512 sets, and in addition all 362880 permutations for the median of nine — not a single error. For comparison, a network with one error was put through the same check — in the last comparator the pair is written in reverse order, CSWAP(p2, p4) instead of CSWAP(p4, p2). The 0-1 check rejected it on 156 sets out of 512, and on all 362880 permutations it returned something other than the median.


76в.8 Where this is needed

Task What to take Why
ADC outlier filter in an interrupt med3_net or med5_net constant and small time in the handler
median filter of a 3 × 3 frame med9_net the same time per pixel — a predictable frame time
rough suppression of frame outliers median of medians 4 medians of three, error of at most one rank
sorting 4–16 elements, for example channels by level a full network no branches, easy to unroll
comparing secrets, keys code without branches the time must not give away the data (43)

76в.9 Pitfalls

The median is "sometimes wrong". The pair in one comparator is written in reverse order. Check the network by the 0-1 principle on all sets — for nine inputs that is only 512 runs.

On M0 the time still floats. The ternary operator on Thumb-1 means branches: 30 of them in the median of nine. If strict constancy is needed — arithmetic min and max.

The median of medians was passed off as the median. In 42.9 % of permutations it is off by one rank. Fine for an outlier filter, not for statistics.

The network is slower than insertion on "calm" data. On a nearly sorted window insertion makes 8 comparisons against 19. A network is chosen for the constancy of time, not for the average.

The values are in int16_t, and min and max are computed through subtraction. The difference of two int16_t in int16_t overflows. Keep the network values in int32_t.


76в.10 Summary

Next: section 76г "Binary heap and priority queue: software timers by deadline on a static array" — how to store dozens of deadlines so that the nearest one is known at once, while starting and cancelling cost log n steps.

Open in the interactive handbook