c / expert
Snippet
Duff's Device for Manual Loop Unrolling
Duff's Device is a famous C idiom that uses a switch statement's fall-through behavior to jump into the middle of a loop. It performs manual loop unrolling, reducing the number of branch instructions and improving performance for bulk data movement.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void fast_copy(int *to, int *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 number of times the unrolled loop body (8 operations) should execute.
2
switch (count % 8) {
Determines the entry point into the loop to handle the remainder elements first.
3
case 0: do { *to++ = *from++;
The 'do' keyword marks the start of the loop, which can be entered at any 'case' label.