Skip to content

Instantly share code, notes, and snippets.

@edvardm
Created September 13, 2017 15:49
Show Gist options
  • Save edvardm/20d28c263662e385ccfa943c80c13445 to your computer and use it in GitHub Desktop.
Save edvardm/20d28c263662e385ccfa943c80c13445 to your computer and use it in GitHub Desktop.
Simple context manager for python cProfiler
import cProfile, pstats, io
class MyProfiler:
def __init__(self):
self.pr = cProfile.Profile()
self.pr.enable()
def __enter__(self):
return self.pr
def __exit__(self, *args):
self.pr.disable()
s = io.StringIO()
ps = pstats.Stats(self.pr, stream=s).sort_stats('cumulative')
ps.print_stats()
print(s.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment