python 中x%2 x&1 判斷偶數奇數 性能對比


本文使用非常好用的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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM