- Loop count is unknown at compile time, so the loop cannot be unrolled
- The loop index
i
is not used within the loop body. In particular it doesn't matter it it's incremented or decremented
void do_something();
static int num;
void loop_1()
{
int i;
for(i = 0; i < num; i++)
do_something();
}
void loop_2()
{
int i = num;
while(i--)
do_something();
}
void loop_3()
{
int i = num+1;
while(--i)
do_something();
}
This code can be compiled with
gcc -O2 -S
. The resulting loop bodies are the following:
loop 1:
.L17:loop 2:
xorl %eax, %eax
addl $1, %ebx
call do_something
cmpl %ebp, %ebx
jne .L17
.L11:loop 3:
xorl %eax, %eax
addl $1, %ebx
call do_something
cmpl %ebp, %ebx
jne .L11
.L5:As you see, the winner is loop 3. Here, the whole logic (without initialization) needs 2 machine instructions:
xorl %eax, %eax
call do_something
subl $1, %ebx
jne .L5
- Decrement
ebx
- Jump is result is nonzero
No comments:
Post a Comment