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 time that the processor executes a loop's completion test and branching instructions compared to the time the processor executes the loop's body. This optimization improves execution speed but increases code size.
Controlling loop unrolling explains how to control the optimization for loop unrolling.
| Turn control this option from here... | use this setting |
|---|---|
| CodeWarrior IDE | Choose an Optimization Level value (3,4) from the Properties > C/C++ Build > Settings > Tool Settings > PowerPC Compiler > Optimization panel. |
| source code | #pragma opt_unroll_loops on | off | reset |
| command line | -opt level=3 , -opt level=4 |
For example, in Before loop unrolling , 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.
In After loop unrolling , 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_from(int* vec)
{
int i;
for (i = 0; i < MAX; ++i)
{
otherfunc(vec[i]);
}
}
const int MAX = 100;
void func_to(int* vec)
{
int i;
for (i = 0; i < MAX;)
{
otherfunc(vec[i]);
++i;
otherfunc(vec[i]);
++i;
}
}