Skip to content

Instantly share code, notes, and snippets.

@benauthor
Created March 27, 2018 22:49
Show Gist options
  • Save benauthor/f42d76f750e9d2099e3e51eed3832ad7 to your computer and use it in GitHub Desktop.
Save benauthor/f42d76f750e9d2099e3e51eed3832ad7 to your computer and use it in GitHub Desktop.
Python profiling decorator
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