Last active
February 9, 2016 19:28
-
-
Save nomeyer/d827e858de135f4509d5 to your computer and use it in GitHub Desktop.
Context manager to profile sqlalchemy query performance
This file contains 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 StringIO | |
import pstats | |
import contextlib | |
@contextlib.contextmanager | |
def profiled(): | |
pr = cProfile.Profile() | |
pr.enable() | |
yield | |
pr.disable() | |
s = StringIO.StringIO() | |
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') | |
ps.print_stats() | |
# uncomment this to see who's calling what | |
# ps.print_callers() | |
print s.getvalue() | |
# To use, wrap the execution of a sqlalchemy query object, like so: | |
with profiled(): | |
data = session.query(TableModel).all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment