timeit与定时装饰(timeit versus timing decorator)

2019-09-01 04:28发布

我想一段代码。 首先,我使用的定时装饰:

#!/usr/bin/env python

import time
from itertools import izip
from random import shuffle

def timing_val(func):
    def wrapper(*arg, **kw):
        '''source: http://www.daniweb.com/code/snippet368.html'''
        t1 = time.time()
        res = func(*arg, **kw)
        t2 = time.time()
        return (t2 - t1), res, func.__name__
    return wrapper

@timing_val
def time_izip(alist, n):
    i = iter(alist)
    return [x for x in izip(*[i] * n)]

@timing_val
def time_indexing(alist, n):
    return [alist[i:i + n] for i in range(0, len(alist), n)]

func_list = [locals()[key] for key in locals().keys()
             if callable(locals()[key]) and key.startswith('time')]
shuffle(func_list)  # Shuffle, just in case the order matters

alist = range(1000000)
times = []
for f in func_list:
    times.append(f(alist, 31))

times.sort(key=lambda x: x[0])
for (time, result, func_name) in times:
    print '%s took %0.3fms.' % (func_name, time * 1000.)

产量

% test.py
time_indexing took 73.230ms.
time_izip took 122.057ms.

在这里,我使用timeit:

%  python - m timeit - s '' 'alist=range(1000000);[alist[i:i+31] for i in range(0, len(alist), 31)]'
10 loops, best of 3:
    64 msec per loop
% python - m timeit - s 'from itertools import izip' 'alist=range(1000000);i=iter(alist);[x for x in izip(*[i]*31)]'
10 loops, best of 3:
    66.5 msec per loop

使用timeit的结果几乎是相同的,但使用它出现的时机装饰time_indexing快于time_izip

是什么导致了这种差异?

要么方法相信?

如果是这样,哪个?

Answer 1:

使用timeit。 运行测试不止一次给了我很多更好的结果。

func_list=[locals()[key] for key in locals().keys() 
           if callable(locals()[key]) and key.startswith('time')]

alist=range(1000000)
times=[]
for f in func_list:
    n = 10
    times.append( min(  t for t,_,_ in (f(alist,31) for i in range(n)))) 

for (time,func_name) in zip(times, func_list):
    print '%s took %0.3fms.' % (func_name, time*1000.)

- >

<function wrapper at 0x01FCB5F0> took 39.000ms.
<function wrapper at 0x01FCB670> took 41.000ms.


Answer 2:

从使用的包装functools改善马特·阿尔科克的答案。

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        print 'func:%r args:[%r, %r] took: %2.4f sec' % \
          (f.__name__, args, kw, te-ts)
        return result
    return wrap

在一个例子:

@timing
def f(a):
    for _ in range(a):
        i = 0
    return -1

调用方法f包裹@timing

func:'f' args:[(100000000,), {}] took: 14.2240 sec
f(100000000)

这样做的好处是,它保留了原有功能的属性; 也就是说,像函数名和文档字符串元数据保存正确的返回功能。



Answer 3:

我会用一个计时装饰,因为您可以使用标注洒在你的代码的时间,而不是让你的代码杂乱与时序逻辑。

import time

def timeit(f):

    def timed(*args, **kw):

        ts = time.time()
        result = f(*args, **kw)
        te = time.time()

        print 'func:%r args:[%r, %r] took: %2.4f sec' % \
          (f.__name__, args, kw, te-ts)
        return result

    return timed

使用装饰很容易要么使用注释。

@timeit
def compute_magic(n):
     #function definition
     #....

或重新别名要时间的函数。

compute_magic = timeit(compute_magic)


Answer 4:

我厌倦了from __main__ import foo ,现在使用此方法-简单ARGS,为此,%R的作品,而不是在IPython中。
(为什么timeit只适用于字符串,而不是的thunk /关闭即timefunc(F,任意参数)?)


import timeit

def timef( funcname, *args, **kwargs ):
    """ timeit a func with args, e.g.
            for window in ( 3, 31, 63, 127, 255 ):
                timef( "filter", window, 0 )
    This doesn't work in ipython;
    see Martelli, "ipython plays weird tricks with __main__" in Stackoverflow        
    """
    argstr = ", ".join([ "%r" % a for a in args]) if args  else ""
    kwargstr = ", ".join([ "%s=%r" % (k,v) for k,v in kwargs.items()]) \
        if kwargs  else ""
    comma = ", " if (argstr and kwargstr)  else ""
    fargs = "%s(%s%s%s)" % (funcname, argstr, comma, kwargstr)
        # print "test timef:", fargs
    t = timeit.Timer( fargs, "from __main__ import %s" % funcname )
    ntime = 3
    print "%.0f usec %s" % (t.timeit( ntime ) * 1e6 / ntime, fargs)

#...............................................................................
if __name__ == "__main__":
    def f( *args, **kwargs ):
        pass

    try:
        from __main__ import f
    except:
        print "ipython plays weird tricks with __main__, timef won't work"
    timef( "f")
    timef( "f", 1 )
    timef( "f", """ a b """ )
    timef( "f", 1, 2 )
    timef( "f", x=3 )
    timef( "f", x=3 )
    timef( "f", 1, 2, x=3, y=4 )

补充:又见“IPython中饰演怪异的招数用 ”,马尔泰利在运行,文档测试,通IPython中



Answer 5:

只是一种猜测,但可以区别是差的大小的范围()值的顺序?

从原始来源:

alist=range(1000000)

从您的timeit例如:

alist=range(100000)

对于它的价值,这里有我的设置为1亿美元之间的系统上的结果:

$ python -V
Python 2.6.4rc2

$ python -m timeit -s 'from itertools import izip' 'alist=range(1000000);i=iter(alist);[x for x in izip(*[i]*31)]'
10 loops, best of 3: 69.6 msec per loop

$ python -m timeit -s '' 'alist=range(1000000);[alist[i:i+31] for i in range(0, len(alist), 31)]'
10 loops, best of 3: 67.6 msec per loop

我是不是能够让你的其他代码运行,因为我无法导入“装饰”模块在我的系统。


更新 -我看你做同样的差异时,我没有参与装饰运行代码。

$ ./test.py
time_indexing took 84.846ms.
time_izip took 132.574ms.

感谢张贴这个问题; 我今天学到了一些东西。 =)



Answer 6:

不管这种特殊的运动,我会想象使用timeit更安全可靠的选择。 它也是跨平台的,不像你的解决方案。



文章来源: timeit versus timing decorator