我试图进入python并使用Mark Lutz" Learning python"为了这。我正准时跟踪锻炼现在。
以下是我用来进行时间跟踪的功能(这些只是书中的副本):
import time, sys
trace = lambda *args: None # or print
timefunc = time.clock if sys.platform == 'win32' else time.time
def timer(func, *pargs, _reps=1000, **kargs):
trace(func, pargs, kargs, _reps)
start = timefunc()
for i in range(_reps):
ret = func(*pargs, **kargs)
elapsed = timefunc() - start
return (elapsed, ret)
def best(func, *pargs, _reps=50, **kargs):
best = 2 ** 32
for i in range(_reps):
(time, ret) = timer(func, *pargs, _reps=1, **kargs)
if time < best: best = time
return (best, ret)
我测试了获得数字平方根的三种方法:math.sqrt
,x**.5
和pow(x, .5)
这是我的主要档案:
from math import sqrt
import mytimer
def stars(x):
return x ** .5
def power(x):
return pow(x, .5)
sqrtmath = mytimer.best(sqrt, 15000, _reps = 1000000)
print(sqrtmath, '\n')
sqrtstars = mytimer.best(stars, 15000, _reps = 1000000)
print(sqrtstars, '\n')
sqrtpow = mytimer.best(power, 15000, _reps = 1000000)
print(sqrtpow, '\n')
sqrtmatha = mytimer.timer(sqrt, 15000, _reps = 1000000)
print(sqrtmatha, '\n')
sqrtstarsa = mytimer.timer(stars, 15000, _reps = 1000000)
print(sqrtstarsa, '\n')
sqrtpowa = mytimer.timer(power, 15000, _reps = 1000000)
print(sqrtpowa, '\n')
我得到的结果与此相似:
math.sqrt best (3.0419786956059625e-07, 122.47448713915891)
** best (3.0419786956059625e-07, 122.47448713915891)
pow best (6.083957391211925e-07, 122.47448713915891)
math.sqrt sum (0.23758340345094187, 122.47448713915891)
** sum (0.4220751526921207, 122.47448713915891)
pow sum (0.48036463590252776, 122.47448713915891)
正如您所看到的,math.sqrt和**版本的最佳时间完全相同,但它们的累积时间差异非常大。怎么会这样?在某个地方有我的错吗?是否有一些我不了解的隐藏蟒蛇机制?