import cProfile import StringIO import pstats import contextlib import time @contextlib.contextmanager def profiled(dbapi): pr = cProfile.Profile() pr.enable() yield pr.disable() pr.dump_stats("profile.stats") s = StringIO.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps.print_stats() print "DBAPI: %s" % dbapi print s.getvalue() @contextlib.contextmanager def timeonly(dbapi): now = time.time() try: yield finally: total = time.time() - now print "DBAPI: %s, total seconds %f" % (dbapi, total) import MySQLdb import pymysql def go(dbapi, ctx): conn = dbapi.connect( user='scott', passwd='tiger', host='192.168.1.117', db='test') cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS test_things ( x INTEGER, y VARCHAR(255), z FLOAT ) engine=InnoDB """) cursor.execute("DELETE from test_things") cursor.close() conn.commit() cursor = conn.cursor() with ctx(dbapi): for row in xrange(1000): cursor.execute( "INSERT INTO test_things (x, y, z) " "VALUES (%(x)s, %(y)s, %(z)s)", {"x": row, "y": "row number %d" % row, "z": row * 4.57292, } ) for x in xrange(500): cursor.execute( "select * from test_things") for row in cursor.fetchall(): row[0], row[1], row[2] cursor.close() conn.close() go(pymysql, profiled) go(MySQLdb, profiled) go(pymysql, timeonly) go(MySQLdb, timeonly)