The decorator used in Decorator for measuring execution time # 1 returned the execution time. To display the execution time while returning the original value of the function to decorate: Although it is output to the standard output by print, I think that it is also good to use a logging module etc.
def time(func):
"""
Debug decorator
Decorator to display effective time
"""
import functools
import datetime
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = datetime.datetime.today()
print '-------------------------------------------------------------'
print func
print '----------------------------------'
print 'start:', start
result = func(*args, **kwargs)
end = datetime.datetime.today()
print 'end:', end
print '----------------------------------'
print 'running:', end - start
print '-------------------------------------------------------------'
return result
return wrapper
I tried using a new decorator for testfunc1 used in Decorator for measuring execution time 1.
>>> testfunc1(rangelist)
-------------------------------------------------------------
<function testfunc1 at 0x01c40590>
----------------------------------
start: 2014-03-21 23:21:01.947000
end: 2014-03-21 23:21:02.362000
----------------------------------
running: 0:00:00.415000
-------------------------------------------------------------
The execution time is displayed properly.
If you don't want to debug and it's a hassle to rewrite the function definition one by one, you can overwrite the time decorator with a do-nothing decorator. As you can see by using it, IPython etc. cannot complete the argument by tab. Since we are using functools.wapas, if you write the docstring properly, the docstring can be displayed even with a function wrapped in a decorator.
def time(func):
"""
Decorator that does nothing
"""
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
Recommended Posts