Skip to content

Instantly share code, notes, and snippets.

@chiragjn
Last active March 18, 2020 18:49
Show Gist options
  • Save chiragjn/97d49ae4bc8b942e96e153a6e38b3a8f to your computer and use it in GitHub Desktop.
Save chiragjn/97d49ae4bc8b942e96e153a6e38b3a8f to your computer and use it in GitHub Desktop.
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,
}
@chiragjn
Copy link
Author

chiragjn commented Nov 27, 2019

Usage

with pyinst():
    # code to profile

Additionally, a dict can be passed as an argument, profiler with add a key 'time' with value equal to the measured time.

exec_info = {}
with pyinst(exec_info):
    # code to profile
print(exec_info['time'])

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