Skip to content

Instantly share code, notes, and snippets.

@Shuhala
Created November 28, 2019 14:57
Show Gist options
  • Save Shuhala/b57940646d84eff6889536b27f5eface to your computer and use it in GitHub Desktop.
Save Shuhala/b57940646d84eff6889536b27f5eface to your computer and use it in GitHub Desktop.
Profile a code block
import cProfile
import contextlib
import io
import pstats
@contextlib.contextmanager
def profile(max_results=-1, pattern="*"):
"""
Profile a code block
:param max_results max number of results to show. -1 means no limit
:param pattern filename pattern to profile. Eg. "module_name"
:see https://docs.python.org/2/library/profile.html
Example:
with profiled():
Session.query(FooClass).filter(FooClass.somevalue==8).all()
Output:
13726 function calls (13042 primitive calls) in 0.014 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
222/21 0.001 0.000 0.011 0.001 lib/sqlalchemy/orm/loading.py:26(instances)
220/20 0.002 0.000 0.010 0.001 lib/sqlalchemy/orm/loading.py:327(_instance)
20 0.000 0.000 0.010 0.000 lib/sqlalchemy/orm/strategies.py:987(load_collection_from_subq)
1 0.000 0.000 0.009 0.009 lib/sqlalchemy/orm/strategies.py:940(_load)
...
"""
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
ps.print_stats(max_results, pattern)
print(s.getvalue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment