gpt4 book ai didi

gcc - C/C++编译器(例如GCC)是否通常以2的幂次幂来优化模数?

转载 作者:行者123 更新时间:2023-12-03 14:45:35 24 4
gpt4 key购买 nike

假设我有类似的东西:

#define SIZE 32

/* ... */

unsigned x;

/* ... */

x %= SIZE;


大多数C / C ++编译器(例如GCC)通常会将 x % 32减小为 x & 31吗?

最佳答案

是的,任何受人尊敬的编译器都应执行此优化。具体来说,其中% X是2的恒定幂的X操作将等同于& (X-1)操作。

GCC甚至会在关闭优化的情况下执行此操作:

示例(Cygwin上的gcc -c -O0版本3.4.4):

unsigned int test(unsigned int a) {
return a % 32;
}


结果(objdump -d):

00000000 <_test>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 5d pop %ebp
7: 83 e0 1f and $0x1f,%eax ;; Here
a: c3 ret

关于gcc - C/C++编译器(例如GCC)是否通常以2的幂次幂来优化模数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22446425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com