Skip to content

Instantly share code, notes, and snippets.

@mijdavis2
Last active July 12, 2019 00:12
Show Gist options
  • Save mijdavis2/f66bec85fdb33d2b46a96c2cdc7f7688 to your computer and use it in GitHub Desktop.
Save mijdavis2/f66bec85fdb33d2b46a96c2cdc7f7688 to your computer and use it in GitHub Desktop.
Decorator for timing functions in python
import time
def timeit(method):
"""
Decorator useful for timing functions.
Source: https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
Usage:
@timeit
def my_function():
pass
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print('%r %2.2f ms' %
(method.__name__, (te - ts) * 1000))
return result
return timed
@jlecount
Copy link

If you changed log_time to be a module var and append times to a list, you could store all call times for all decorated functions without the need to pass in the kwarg. Then after the end of your program, before exit, you could post-process (average, stats, graph, whatever) the log_time data at that point. No need to inject it into the function kwargs then. Which also saves you from having to change all timed functions to accept **kwargs. Maybe some don't etc....

@mijdavis2
Copy link
Author

👍 to your comment @jlecount. That's a great idea. Will allow for more portability of the decorator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment