[Python] timeit測試代碼運行效率
阿新 • • 發佈:2018-10-19
for 利用 一個 loop 偶數 求余 與操作 操作 兩種
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)
deftest2(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)
結果顯而易見
[Python] timeit測試代碼運行效率