Last active
March 18, 2020 18:49
-
-
Save chiragjn/97d49ae4bc8b942e96e153a6e38b3a8f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 contextlib import contextmanager | |
import cProfile, pstats, io | |
from timeit import default_timer as timer | |
from pyinstrument import Profiler | |
from pyinstrument.renderers import ConsoleRenderer | |
@contextmanager | |
def pyinst(r=None): | |
r = {} if r is None else r | |
profiler = Profiler() | |
profiler.start() | |
yield | |
session = profiler.stop() | |
profile_renderer = ConsoleRenderer(unicode=True, color=True, show_all=True) | |
print(profile_renderer.render(session)) | |
r['time'] = session.to_json()['duration'] | |
print(r) | |
@contextmanager | |
def cprof(r=None): | |
r = {} if r is None else r | |
pr = cProfile.Profile() | |
pr.enable() | |
yield | |
pr.disable() | |
s = io.StringIO() | |
sortby = 'cumulative' | |
ps = pstats.Stats(pr, stream=s).sort_stats(sortby) | |
ps.print_stats() | |
print(s.getvalue()) | |
r['time'] = ps.total_tt | |
print(r) | |
@contextmanager | |
def simple_timer(r=None): | |
r = {} if r is None else r | |
start = timer() | |
yield | |
end = timer() | |
r['time'] = end - start | |
print(r) | |
PROFILERS = { | |
'pyinst': pyinst, | |
'cprof': cprof, | |
'simple_timer': simple_timer, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Additionally, a dict can be passed as an argument, profiler with add a key 'time' with value equal to the measured time.