ken*_*ytm 57
众所周知
static inline int is_odd_A(int x) { return x & 1; }
Run Code Online (Sandbox Code Playgroud)
效率比
static inline int is_odd_B(int x) { return x % 2; }
Run Code Online (Sandbox Code Playgroud)
但是随着优化器的开启,将会is_odd_B
有什么不同is_odd_A
?不 - gcc-4.2 -O2
我们得到,(在ARM组装中):
_is_odd_A:
and r0, r0, #1
bx lr
_is_odd_B:
mov r3, r0, lsr #31
add r0, r0, r3
and r0, r0, #1
rsb r0, r3, r0
bx lr
Run Code Online (Sandbox Code Playgroud)
我们看到它is_odd_B
需要多3个指令is_odd_A
,主要原因是因为
((-1) % 2) == -1
((-1) & 1) == 1
Run Code Online (Sandbox Code Playgroud)
但是,以下所有版本都将生成相同的代码is_odd_A
:
#include <stdbool.h>
static inline bool is_odd_D(int x) { return x % 2; } // note the bool
static inline int is_odd_E(int x) { return x % 2 != 0; } // note the !=
Run Code Online (Sandbox Code Playgroud)
这是什么意思?优化器通常足够复杂,对于这些简单的东西,最清晰的代码足以保证最佳效率.
通常的方式:
int number = ...;
if(number % 2) { odd }
else { even }
Run Code Online (Sandbox Code Playgroud)
替代方案:
int number = ...;
if(number & 1) { odd }
else { even }
Run Code Online (Sandbox Code Playgroud)
在GCC 3.3.1和4.3.2上测试,两者都具有大约相同的速度(没有编译器优化),因为两者都导致and
指令(在x86上编译) - 我知道使用div
模数指令会慢得多,因此我没有根本不测试它.
bool is_odd = number & 1;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18489 次 |
最近记录: |