Created
December 14, 2020 14:52
-
-
Save gabrieldernbach/db96c9654c9dbc016106383dff7daedb to your computer and use it in GitHub Desktop.
Profiler
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
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dummy code, NOT TESTED YET