Created
March 27, 2018 22:49
-
-
Save benauthor/f42d76f750e9d2099e3e51eed3832ad7 to your computer and use it in GitHub Desktop.
Python profiling decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cProfile import Profile | |
from functools import wraps | |
import pstats | |
def profiled(f): | |
""" | |
Decorator for profiling a function | |
To use: | |
- decorate function | |
- execute the code path | |
- browse the results via `python -m pstats /tmp/weatherhub_profiling` | |
(docs https://docs.python.org/3/library/profile.html ... try: | |
`strip`, `sort time`, `stats 10`) | |
""" | |
@wraps(f) | |
def _wrapper(*args, **kwargs): | |
pr = Profile() | |
pr.enable() | |
try: | |
result = f(*args, **kwargs) | |
except Exception: # pylint: disable=broad-except | |
raise | |
finally: | |
pr.disable() | |
ps = pstats.Stats(pr) | |
ps.dump_stats("/tmp/profiling") | |
return result | |
return _wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment