Use wrapping from functools
to improve Matt Alcock’s answer.
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
In an example:
@timing
def f(a):
for _ in range(a):
i = 0
return -1
Invoking method f
wrapped with @timing
:
func:'f' args:[(100000000,), {}] took: 14.2240 sec
f(100000000)
The advantage of this is that it preserves attributes of the original function; that is, metadata like the function name and docstring is correctly preserved on the returned function.