Skip to content

Instantly share code, notes, and snippets.

@gwax
Created May 11, 2016 17:47
Show Gist options
  • Save gwax/3d7e21fe9694909eaec464db71fdf51a to your computer and use it in GitHub Desktop.
Save gwax/3d7e21fe9694909eaec464db71fdf51a to your computer and use it in GitHub Desktop.
Profiling stuff
"""Profiling code."""
import cProfile
import io
import pstats
import contextlib
def start():
"""Start and return profiler."""
profiler = cProfile.Profile()
profiler.enable()
return profiler
def finish(profiler):
"""Stop the profiler and print out stats."""
profiler.disable()
out_stream = io.StringIO()
profile_stats = pstats.Stats(
profiler, stream=out_stream).sort_stats('cumulative')
profile_stats.print_stats(30)
print(out_stream.getvalue())
@contextlib.contextmanager
def profiled(enabled):
"""Context manager to profile within a given context."""
profiler = None
if enabled:
profiler = start()
try:
yield
finally:
if profiler is not None:
finish(profiler)
@jiffyclub
Copy link

This would be great if it included the option of dumping the stats to a file. You can do that in finish by calling profile_stats.dump_stats.

Then users can load the stats file at the console using pstats.Stats and have the option of sorting the data in different ways. They can also pass the file to SnakeViz to visualize the call tree and execution time.

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