Skip to content

Instantly share code, notes, and snippets.

@beledouxdenis
Last active September 12, 2019 12:00
Show Gist options
  • Save beledouxdenis/eced75215054c25757179bdcc414ed75 to your computer and use it in GitHub Desktop.
Save beledouxdenis/eced75215054c25757179bdcc414ed75 to your computer and use it in GitHub Desktop.
# Add the below code in your Python file,
# then add @own_profiler as a decorator on the method you would like to profile.
# Note:
# - If there is already a decorator on the method, set @own_profiler above,
# - Each time the method is called, it generates a new profile file,
# don't set this decorator on a method called hundred of times or you will have hundred of profile files to analyze.
#
# To display the resulting profiling data file:
#
# Snakeviz: Callstack layer graph & stats table
# sudo pip3 install snakeviz
# snakeviz /tmp/profile.prof
#
# gprof2dot: Tree graph
# sudo apt install graphviz && sudo pip3 install gprof2dot
# gprof2dot -f pstats /tmp/profile.prof | dot -Tpng -o /tmp/profile.png
import cProfile
import functools
import time as T
def own_profiler(func):
@functools.wraps(func)
def inner(*args, **kwargs):
profiler = cProfile.Profile()
profiler.enable()
try:
retval = func(*args, **kwargs)
finally:
profiler.disable()
profiler.dump_stats('/tmp/profile.%s.prof' % (T.strftime("%Y-%d-%m_%H-%M-%S")))
return retval
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment