Skip to content

Instantly share code, notes, and snippets.

@gabrieldernbach
Created December 14, 2020 14:52
Show Gist options
  • Save gabrieldernbach/db96c9654c9dbc016106383dff7daedb to your computer and use it in GitHub Desktop.
Save gabrieldernbach/db96c9654c9dbc016106383dff7daedb to your computer and use it in GitHub Desktop.
Profiler
import cProfile
import pstats
import io
def profile(file_path=None, breakpoint_after_call=False):
"""decorator for runtime profiling of functions or class methods
prints the profiling statistics sorted by
cumulative time,
total time,
number of calls
Args:
file_path: write log to disk
breakpoint_after_call: drop into pdb after execution for live
insepction of the logs.
"""
def inner(function):
def wrapped(*args, **kwargs):
profiler = cProfile.Profile()
profiler.enable()
out = function(*args, **kwargs)
profiler.disable()
s = io.StringIO()
stats = pstats.Stats(profiler, stream=s)
for key in ["cumulative", "total", "calls"]:
sorted_stats = stats.sort_stats(key)
sorted_stats.print_stats()
if file_path:
sorted_stats.dump_stats(f"{file_path}/{key}.log")
if breakpoint_after_call:
breakpoint()
return out
return wrapped
return inner
@gabrieldernbach
Copy link
Author

Dummy code, NOT TESTED YET

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