哪个更快找到偶数if(n%2 == 0)或if(n& 1 == 0)? [英] which is faster to find the even number if(n%2==0) or if(n&1==0)?
本文介绍了哪个更快找到偶数if(n%2 == 0)或if(n& 1 == 0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以更快的速度找到偶数if(n%2 == 0)或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
推荐答案
这看起来像Python,所以我在Python(3.6)中尝试过:
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)
时间变化很大(谢谢,垃圾收集器!),但是总的来说,这让我获得 i%2
大约4.7秒,获得 i& 1
大约6.3秒.我想这可能不是您期望的答案.
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.
我使用dis检查了字节码,唯一的区别是运行BINARY_MODULO与BINARY_AND的一行,所以我不确定为什么会有如此大的时间差异.
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.
这篇关于哪个更快找到偶数if(n%2 == 0)或if(n& 1 == 0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文