【问题标题】:Decorator for timeit.timeit method?timeit.timeit 方法的装饰器?
【发布时间】:2019-01-01 08:58:55
【问题描述】:

我正在尝试编写一个简单的时间装饰器来测量函数所花费的时间。然而,下面的代码给出了我们的递归错误。它有什么问题?

import timeit

def measure(func):
    def wrapper():
        func_name = func.__name__
        setup="from __main__ import {}".format(func_name)
        op_time = timeit.timeit('{}()'.format(func_name), number = 2, setup=setup)
        print(ot)
    return wrapper

@measure
def sample():
    return 10

sample()

输出

RecursionError                            Traceback (most recent call last)
<ipython-input-61-e079e1bd7fba> in <module>()
     15     return 10
     16
---> 17 sample()

<ipython-input-61-e079e1bd7fba> in wrapper()
      7         func_name = func.__name__
      8         setup="from __main__ import {}".format(func_name)
----> 9         op_time = timeit.timeit('{}()'.format(func_name), number = 2, setup=setup)
     10         print(ot)
     11     return wrapper

~/anaconda3/lib/python3.6/timeit.py in timeit(stmt, setup, timer, number, globals)
    231            number=default_number, globals=None):
    232     """Convenience function to create Timer object and call timeit method."""
--> 233     return Timer(stmt, setup, timer, globals).timeit(number)
    234
    235 def repeat(stmt="pass", setup="pass", timer=default_timer,

~/anaconda3/lib/python3.6/timeit.py in timeit(self, number)
    176         gc.disable()
    177         try:
--> 178             timing = self.inner(it, self.timer)
    179         finally:
    180             if gcold:

~/anaconda3/lib/python3.6/timeit.py in inner(_it, _timer)

... last 4 frames repeated, from the frame below ...

<ipython-input-61-e079e1bd7fba> in wrapper()
      7         func_name = func.__name__
      8         setup="from __main__ import {}".format(func_name)
----> 9         op_time = timeit.timeit('{}()'.format(func_name), number = 2, setup=setup)
     10         print(ot)
     11     return wrapper

RecursionError: maximum recursion depth exceeded while calling a Python object

我有兴趣了解我现有代码的问题,请不要发布替代解决方案。

【问题讨论】:

  • 你不能有这样的函数时间本身,因为你计时的方式运行函数,对函数计时,运行函数......

标签: python decorator python-decorators timeit


【解决方案1】:
from functools import wraps
from time import time
def measure(func):
    @wraps(func)
    def _time_it(*args, **kwargs):
        start = int(round(time() * 1000))
        try:
            return func(*args, **kwargs)
        finally:
            end_ = int(round(time() * 1000)) - start
            print(f"Total execution time: {end_ if end_ > 0 else 0} ms")
    return _time_it
@measure
def hello():
    print('hello world')

hello()

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 2014-04-08
    • 2020-01-02
    • 2020-02-05
    • 2018-07-14
    相关资源
    最近更新 更多