C
Loop optimization
Learn loop optimization and unrolling.
Loop optimization
Loop unrolling processes multiple elements per iteration to reduce the loop count. This reduces loop overhead (condition check, increment) and increases instruction-level parallelism.
A 4-way unroll example: for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }. Each iteration handles 4 elements; the loop count is divided by 4. A second loop handles the remaining elements. Modern compilers do this automatically; writing it by hand at advanced level gives further gains.
Remaining elements
4-way unroll misses some elements when the array size is not a multiple of 4. So you add a remainder loop for (; i < n; i++) sum += a[i];.
Example: the 8-element array {1,2,3,4,5,6,7,8} is handled in two unrolled iterations (i=0, i=4) with no remainder; the sum is 36. With 10 elements, 8 would go through the unroll and 2 through the remainder. This pattern is required for both performance and correctness.
Exercise 4-way unrolled sum
Write int sum_unrolled(int *a, int n): int sum = 0; int i;, loop for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }, remainder for (; i < n; i++) sum += a[i];, return sum;. In main declare int a[] = {1,2,3,4,5,6,7,8}; and print printf("toplam: %d\n", sum_unrolled(a, 8));.
Show example solution
#include <stdio.h>
int sum_unrolled(int *a, int n) {
int sum = 0;
int i;
for (i = 0; i + 3 < n; i += 4) {
sum += a[i] + a[i+1] + a[i+2] + a[i+3];
}
for (; i < n; i++) sum += a[i];
return sum;
}
int main(void) {
int a[] = {1,2,3,4,5,6,7,8};
printf("toplam: %d\n", sum_unrolled(a, 8));
return 0;
}
Test yourself
-
4-way unroll step
for (i = 0; i + 3 < n; i += ____) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }
Show answer
for (i = 0; i + 3 < n; i += 4) { sum += a[i] + a[i+1] + a[i+2] + a[i+3]; }
-
Match loop concepts
- unroll
- Multiple elements
- i += 4
- 4-way step
- remainder loop
- Leftover elements
- condition check
- Loop overhead
-
What does loop unrolling reduce?
- Memory usage
- File size
- Loop overhead
- Line count
Show answer
Loop overhead — Unrolling reduces loop overhead (condition, increment).
Next lesson: inline