Division by powers of 2 is faster with unsigned int
, because it can be optimized into a single shift instruction. With signed int
, it usually requires more machine instructions, because division rounds towards zero, but shifting to the right rounds down. Example:
int foo(int x, unsigned y)
{
x /= 8;
y /= 8;
return x + y;
}
Here is the relevant x
part (signed division):
movl 8(%ebp), %eax
leal 7(%eax), %edx
testl %eax, %eax
cmovs %edx, %eax
sarl $3, %eax
And here is the relevant y
part (unsigned division):
movl 12(%ebp), %edx
shrl $3, %edx
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…