gpt4 book ai didi

c - 查找数字是偶数还是奇数的最快方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:19:26 24 4
gpt4 key购买 nike

判断一个数是偶数还是奇数的最快方法是什么?

最佳答案

众所周知

static inline int is_odd_A(int x) { return x & 1; }

更有效率
static inline int is_odd_B(int x) { return x % 2; }

但是启用优化器后,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

我们看到is_odd_Bis_odd_A多了3条指令,主要原因是因为

((-1) % 2) == -1
((-1) & 1) == 1

但是,以下所有版本都会生成与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 !=

这是什么意思?优化器通常足够复杂,对于这些简单的东西,最清晰的代码足以保证最佳效率

关于c - 查找数字是偶数还是奇数的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229107/

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