什么是找到一个数是偶数或奇数的最快方法? [英] What is the fastest way to find if a number is even or odd?

查看:245
本文介绍了什么是找到一个数是偶数或奇数的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是找到最快的方法,如果一个号码偶数或奇数?

What is the fastest way to find if a number is even or odd?

推荐答案

有pretty众所周知,

It is pretty well known that

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汇编):

But with the optimizer on, will is_odd_B be no different from is_odd_A? No — with gcc-4.2 -O2, we get, (in ARM assembly):

_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_B 花费的时间比 is_odd_A 3的更多说明,主要的原因是因为

We see that is_odd_B takes 3 more instructions than is_odd_A, the main reason is because

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

然而,下面所有的版本将生成相同的code作为 is_odd_A

However, all the following versions will generate the same code as 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 !=

这是什么意思?优化通常是复杂的,以至于,对于这些简单的东西,清亮code是足以保证最佳的效率

这篇关于什么是找到一个数是偶数或奇数的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆