本文使用非常好用的python交互解釋器ipython操作演示,
使用命令pip install ipython安裝,輸入ipython即可。比python自帶的好用。
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
性能肯定是&1更高嘛,實際當中感覺差不多,簡單寫兩個函數測試一下
二進制與操作&1判斷偶奇數:
def testand(x):
for r in range(1,x):
if r&1:
pass
%2求余判斷偶奇數:
def testmod(x):
for r in range(1,x):
if r%2:
pass
用ipython自帶的timeit功能測試:
In [19]: %timeit testmod(100000)
100 loops, best of 3: 12.9 ms per loop
In [20]: %timeit testand(100000)
100 loops, best of 3: 10.8 ms per loop
In [21]: %timeit testand(1000000)
10 loops, best of 3: 109 ms per loop
In [22]: %timeit testmod(1000000)
10 loops, best of 3: 129 ms per loop
對我來說,感覺差距不大。
In [162]: %timeit testand(999999)
10 loops, best of 3: 109 ms per loop
In [163]: %timeit testand(9999999)
1 loop, best of 3: 1.08 s per loop
In [164]: %timeit testand(99999999)
1 loop, best of 3: 10.9 s per loop
In [165]: %timeit testmod(9999999)
1 loop, best of 3: 1.3 s per loop
In [166]: %timeit testmod(99999999)
1 loop, best of 3: 13 s per loop
&1確實性能更好,加大了數據,不過差距也沒有很明顯放大。
2016年10月9日 13:46:36 codegay