python中有两种方法判断一个数是不是偶数或者奇数:

In [29]: 3&1
Out[29]: 1

In [30]: 3%2
Out[30]: 1

In [31]: 4&1
Out[31]: 0

In [32]: 4%2
Out[32]: 0

当不知道 采用 % 或 & 哪种 判断 奇偶的方法运行效率更高的时候

利用python timeit来测定

二进制与操作&1判断偶奇数:
def test1(x):
    for r in range(1,x):
        if r&1:
            pass
%2求余判断偶奇数:
def test2(x):
    for r in range(1,x):
        if r%2:
            pass

 

测试函数

def test1(x):
    for r in range(1,x):
        if r&1:
            pass

%timeit test1(1000000)
60.6 ms ± 1.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
def test2(x):
    for r in range(1,x):
        if r%2:
            pass

%timeit test2(1000000)
48.7 ms ± 766 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

结果显而易见

 

相关文章:

  • 2021-06-02
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-04
  • 2021-08-21
猜你喜欢
  • 2021-06-19
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2022-01-02
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案