Last active
February 25, 2019 16:45
-
-
Save mklymyshyn/8ffc63fd901c6de7073c18ae023d5cbc to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python2.7 | |
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_conf.py wsgi | |
# ** TIME MEASUREMENTS ONLY: | |
$ PROFILER=0 gunicorn -c ./wsgi_profiler_conf.py wsgi | |
""" | |
def profiler_enable(worker, req): | |
worker.profile = cProfile.Profile() | |
worker.profile.enable() | |
worker.log.info("PROFILING %d: %s" % (worker.pid, req.uri)) | |
def profiler_summary(worker, req): | |
s = StringIO.StringIO() | |
worker.profile.disable() | |
ps = pstats.Stats(worker.profile, stream=s).sort_stats('time', 'cumulative') | |
ps.print_stats(PROFILE_LIMIT) | |
logging.error("\n[%d] [INFO] [%s] URI %s" % (worker.pid, req.method, req.uri)) | |
logging.error("[%d] [INFO] %s" % (worker.pid, 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" % ( | |
worker.pid, 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