Decorator for timeit.timeit method?

China☆狼群 提交于 2020-12-01 07:45:25

问题


I'm trying to write a simple time decorator to measure time taken by functions. However the code below is giving our recursion error. What's wrong with it?

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()

Output

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

I'm interested in learning what's wrong with my existing code, please don't post alternative solutions.


回答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()


来源:https://stackoverflow.com/questions/51503672/decorator-for-timeit-timeit-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!