时间跟踪数据不匹配

时间:2017-02-24 19:57:25

标签: python python-3.x time-tracking

我试图进入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.sqrtx**.5pow(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和**版本的最佳时间完全相同,但它们的累积时间差异非常大。怎么会这样?在某个地方有我的错吗?是否有一些我不了解的隐藏蟒蛇机制?

0 个答案:

没有答案