Loop unrolling inserts extra copies of a loop's body in a loop to reduce processor time executing a loop's overhead instructions for each iteration of the loop body. In other words, this optimization attempts to reduce the ratio of the time that the processor takes to execute a loop's completion test and the branching instructions, compared to the time the processor takes to execute the loop's body. This optimization improves execution speed but increases code size.
The following table explains how to control the optimization for loop unrolling.
| Turn control this option from here... | use this setting |
|---|---|
| CodeWarrior IDE | Choose Level 3 or Level 4 in the Optimization Level settings panel. |
| source code | #pragma opt_unroll_loops on | off | reset |
| command line | -opt level=3, -opt level=4 |
For example, in the following listing, the for loop's body is a single call to a function, otherfunc(). For each time the loop's completion test executes
for (i = 0; i < MAX; ++i)
the function executes the loop body only once.
const int MAX = 100; void func_from(int* vec) { int i; for (i = 0; i < MAX; ++i) { otherfunc(vec[i]); } }
In the following listing, the compiler has inserted another copy of the loop body and rearranged the loop to ensure that variable i is incremented properly. With this arrangement, the loop's completion test executes once for every 2 times that the loop body executes.
const int MAX = 100; void func_to(int* vec) { int i; for (i = 0; i < MAX;) { otherfunc(vec[i]); ++i; otherfunc(vec[i]); ++i; } }