难道一个C / C ++编译器通过优化电源的二值恒师为转移? [英] Does a c/c++ compiler optimize constant divisions by power-of-two value into shifts?
问题描述
问题说明了一切。有谁知道,如果下面...
Question says it all. Does anyone know if the following...
size_t div(size_t value) {
const size_t x = 64;
return value / x;
}
...被优化成?
...is optimized into?
size_t div(size_t value) {
return value >> 6;
}
不要编译器这样做呢? (我的兴趣在于GCC)。有没有在那里它的情况和其他地方不?
Do compilers do this? (My interest lies in GCC). Are there situations where it does and others where it doesn't?
我真的很想知道,因为我每次写,可以这样进行优化,我花费了一些精力想知道是否第二的precious空话被浪费在做了分工,其中的转变就足够一个部门。
I would really like to know, because every time I write a division that could be optimized like this I spend some mental energy wondering about whether precious nothings of a second is wasted doing a division where a shift would suffice.
推荐答案
即使 G ++ -O0
(是的, -O0
!),这种情况发生。你的函数编译为:
Even with g++ -O0
(yes, -O0
!), this happens. Your function compiles down to:
_Z3divm:
.LFB952:
pushq %rbp
.LCFI0:
movq %rsp, %rbp
.LCFI1:
movq %rdi, -24(%rbp)
movq $64, -8(%rbp)
movq -24(%rbp), %rax
shrq $6, %rax
leave
ret
请注意在 SHRQ $ 6
,这是由6位右移。
Note the shrq $6
, which is a right shift by 6 places.
使用 -O1
,不必要的垃圾被删除:
With -O1
, the unnecessary junk is removed:
_Z3divm:
.LFB1023:
movq %rdi, %rax
shrq $6, %rax
ret
结果在G ++ 4.3.3,64。
Results on g++ 4.3.3, x64.
这篇关于难道一个C / C ++编译器通过优化电源的二值恒师为转移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!