which is faster to find the even number if(n%2==0) or if(n&1==0)? [duplicate]

孤者浪人 提交于 2021-02-08 12:10:22

问题


which is faster to find the even number if(n%2==0) or if(n&1==0) ?

def isEven(n):
    if n%2 == 0:
        return True
    return False
OR

def isEven(n):
    if n&1 == 1:
        return False
    return True

回答1:


This looks like Python, so I tried it in Python(3.6):

from timeit import timeit
a = timeit(stmt='for i in range(100): i%2')
b = timeit(stmt='for i in range(100): i&1')
print(a, b)

Times vary somewhat wildly (thanks, garbage collector!) but in general this gets me around 4.7 seconds for i%2 and 6.3 seconds for i&1, which I would guess is probably not the answer you would expect.

I checked the bytecode using dis, and the only difference was the one line running BINARY_MODULO vs BINARY_AND, so I'm not sure why there's such a huge time discrepancy.




回答2:


I would expect reasonable optimizing compilers for languages where those expressions are equivalent to implement both options equivalently.

In fact, I tried four different C++ compilers: gcc, clang, MSVC and icc and while every compiler implemented the idioms differently from the other compilers1, three out of four compilers implemented both idioms the same way.

Only icc generated different code, and in that case (n & 1) == 0 generated much better code than n % 2 == 0 - but you should consider that an icc bug.

However, not all languages implement optimizing compilers (ahead of time or JIT), and in particular interpreters may or may not optimize this similarly. If you are interested in a specific language or platform, you might consider tagging your question to reflect that.


1 That's actually surprising and unusual for such simple code. Overall clang generated the best code, followed by MSVC and then gcc. icc generated really terrible code for the n % 2 option. Weirdly, gcc generates strictly better code at -O1 than -O2.



来源:https://stackoverflow.com/questions/51597019/which-is-faster-to-find-the-even-number-ifn2-0-or-ifn1-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!