Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import cProfile
import pstats
import StringIO
import logging
import os
import time
PROFILE_LIMIT = int(os.environ.get("PROFILE_LIMIT", 30))
PROFILER = bool(int(os.environ.get("PROFILER", 1)))
print """
# ** USAGE:
$ PROFILE_LIMIT=100 gunicorn -c ./ wsgi
$ PROFILER=0 gunicorn -c ./ wsgi
def profiler_enable(worker, req):
worker.profile = cProfile.Profile()
worker.profile.enable()"PROFILING %d: %s" % (, req.uri))
def profiler_summary(worker, req):
s = StringIO.StringIO()
ps = pstats.Stats(worker.profile, stream=s).sort_stats('time', 'cumulative')
logging.error("\n[%d] [INFO] [%s] URI %s" % (, req.method, req.uri))
logging.error("[%d] [INFO] %s" % (, unicode(s.getvalue())))
def pre_request(worker, req):
worker.start_time = time.time()
if PROFILER is True:
profiler_enable(worker, req)
def post_request(worker, req, *args):
total_time = time.time() - worker.start_time
logging.error("\n[%d] [INFO] [%s] Load Time: %.3fs\n" % (, req.method, total_time))
if PROFILER is True:
profiler_summary(worker, req)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.