-
-
Save bhardwajRahul/323e9fb0afdce338f6db936aeb04af12 to your computer and use it in GitHub Desktop.
Profile a code block
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
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