主要有如下三種方式:性能
一,CPU時間
time.clock()this
測量CPU時間,比較精準,經過比較程序運行先後的CPU時間差,得出程序運行的CPU時間。spa
二, 時鐘時間
time.time()code
測量時鐘時間,也就是一般的相似掐表計時。blog
三,基準時間
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000) get
簡短示例:it
timeit(「math.sqrt(2.0)」, 「import math」)class
timeit(「sqrt(2.0)」, 「from ,math import sqrt」)test
timeit(「test()」, 「from __main__ import test」, number = 10000)import
示例(示例中的三個方法都是求解一個數的因子數的個數)
CPU時間的示例:
Code1import time
def countDiv(n):
"Return the count number of divisors of n."
count = 1
for i in range(1, n):
if n%i == 0:
count += 1
return count
def countDiv2(n):
return len([x for x in range(1, n+1) if n%x == 0])
def countDiv3(n):
s = set()
for i in range(1, n):
if i in s:
break
else:
if n%i == 0:
s.update({i, n/i})
return len(s)
start_CPU = time.clock()
a = countDiv(73920)
end_CPU = time.clock()
print("Method 1: %f CPU seconds" % (end_CPU - start_CPU))
start_CPU = time.clock()
a = countDiv2(73920)
end_CPU = time.clock()
print("Method 2: %f CPU seconds" % (end_CPU - start_CPU))
start_CPU = time.clock()
a = countDiv3(73920)
end_CPU = time.clock()
print("Method 3: %f CPU seconds" % (end_CPU - start_CPU))
結果:最快的是方法三,方法二和方法一,其實不相上下.
Result1Method 1: 0.022805 CPU seconds
Method 2: 0.015988 CPU seconds
Method 3: 0.000141 CPU seconds
時鐘時間示例:
Code2import time
start_Real = time.time()
a = countDiv(73920)
end_End = time.time()
print("Method 1: %f real seconds" % (end_End - start_Real))
start_Real = time.time()
a = countDiv2(73920)
end_End = time.time()
print("Method 2: %f real seconds" % (end_End - start_Real))
start_Real = time.time()
a = countDiv3(73920)
end_End = time.time()
print("Method 3: %f real seconds" % (end_End - start_Real))
結果:
Result2Method 1: 0.016001 real seconds
Method 2: 0.016001 real seconds
Method 3: 0.000000 real seconds
在精度不夠的狀況下,都沒法得知,方法三真正的運行時間.
真的想知道,方法三比方法一或者二快多少倍,仍是要使用timeit。timeit能夠重複執行代碼必定次數,這樣更加穩定的反應程序的執行時間,不會由於一次的執行而產生較大的偏差。
Code3if __name__ == '__main__':
import timeit
print(timeit.timeit("countDiv(73920)", setup = "from __main__ import countDiv", number=100))
print(timeit.timeit("countDiv2(73920)", setup = "from __main__ import countDiv2", number=100))
print(timeit.timeit("countDiv3(73920)", setup = "from __main__ import countDiv3", number=100))
結果:
Result31.6992941682537246
1.69091280670973
0.013773491283526784
經過timeit能夠看出,方法二基本和方法一的性能是相同的。timeit返回是時鐘時間。方法二,基本是方法三耗時的130倍左右。