Skip to content

Instantly share code, notes, and snippets.

@nomeyer
Last active February 9, 2016 19:28
Show Gist options
  • Save nomeyer/d827e858de135f4509d5 to your computer and use it in GitHub Desktop.
Save nomeyer/d827e858de135f4509d5 to your computer and use it in GitHub Desktop.
Context manager to profile sqlalchemy query performance
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