Skip to content

Instantly share code, notes, and snippets.

@gurel
Created April 27, 2015 15:05
Show Gist options
  • Save gurel/d7634c9640a08b96c0ea to your computer and use it in GitHub Desktop.
Save gurel/d7634c9640a08b96c0ea to your computer and use it in GitHub Desktop.
Sql Alchemy Profiling
from sqlalchemy import event
from sqlalchemy.engine import Engine
import time
import logging
logging.basicConfig()
logger = logging.getLogger("myapp.sqltime")
logger.setLevel(logging.DEBUG)
@event.listens_for(Engine, "before_cursor_execute")
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
conn.info.setdefault('query_start_time', []).append(time.time())
logger.debug("Start Query: %s", statement)
@event.listens_for(Engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
total = time.time() - conn.info['query_start_time'].pop(-1)
logger.debug("Query Complete!")
logger.debug("Total Time: %f", total)
"""
DEBUG:myapp.sqltime:Start Query: SELECT `CampaignGroups`.`CampaignGroupID` AS `CampaignGroups_CampaignGroupID`
FROM `CampaignGroups`
WHERE `CampaignGroups`.`CampaignGroupFacebookID` IN (%s)
DEBUG:myapp.sqltime:Query Complete!
DEBUG:myapp.sqltime:Total Time: 0.002063
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment