c / expert
Snippet
Duff's Device for Manual Loop Unrolling
Duff's Device is a famous C idiom that implements loop unrolling by interweaving a switch statement with a do-while loop. This allows the program to jump into the middle of the loop to handle the remainder of elements when the total count is not a multiple of the unroll factor (8 in this case). It minimizes the number of branch instructions and loop overhead.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void dcopy(short *to, short *from, int count) {int n = (count + 7) / 8;switch (count % 8) {case 0: do { *to = *from++;case 7: *to = *from++;case 6: *to = *from++;case 5: *to = *from++;case 4: *to = *from++;case 3: *to = *from++;case 2: *to = *from++;case 1: *to = *from++;} while (--n > 0);}}
Breakdown
1
int n = (count + 7) / 8;
Calculates the total number of iterations needed for the unrolled blocks.
2
switch (count % 8) {
Determines the entry point into the loop based on the remainder.
3
case 0: do { *to = *from++;
The loop start; case 0 handles counts that are exact multiples of 8.
4
} while (--n > 0);
Decrements the block counter and repeats the unrolled 8-step process.