主要有以下三种方式:
一,CPU时间
time.clock()
测量CPU时间,比较精准,通过比较程序运行前后的CPU时间差,得出程序运行的CPU时间。
二, 时钟时间
time.time()
测量时钟时间,也就是通常的类似掐表计时。
三,基准时间
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
简短示例:
timeit(“math.sqrt(2.0)”, “import math”)
timeit(“sqrt(2.0)”, “from ,math import sqrt”)
timeit(“test()”, “from __main__ import test”, number = 10000)
示例(示例中的三个方法都是求解一个数的因子数的个数)
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倍左右。