Skip to content

Instantly share code, notes, and snippets.

@eirenik0
Last active February 15, 2017 15:28
Show Gist options
  • Save eirenik0/7a8c5ab7a374d97c407fb5c008d180a6 to your computer and use it in GitHub Desktop.
Save eirenik0/7a8c5ab7a374d97c407fb5c008d180a6 to your computer and use it in GitHub Desktop.
Django middelware profiler
import cProfile, pstats, StringIO
class ProfileMiddleware(object):
def process_request(self, request):
pr = cProfile.Profile()
pr.enable()
request._pr = pr
def process_response(self, request, response):
request._pr.disable()
s = open('/tmp/demo_app.prof', 'a+')
sortby = 'cumulative'
# Sort the output by cumulative time it took in fuctions/methods.
ps = pstats.Stats(request._pr, stream=s).sort_stats(sortby)
# Print only 10 most time consuming functions
ps.print_stats(100)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment