Login

Profiling middleware using cProfile

Author:
sgb
Posted:
April 27, 2008
Language:
Python
Version:
.96
Tags:
middleware performance profiler
Score:
5 (after 5 ratings)

Similar to Profiling Middleware, but uses cProfile instead of hotshot.

Append ?prof to the URL to see profiling output instead of page output.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import sys
import cProfile
from cStringIO import StringIO
from django.conf import settings

class ProfilerMiddleware(object):
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if settings.DEBUG and 'prof' in request.GET:
            self.profiler = cProfile.Profile()
            args = (request,) + callback_args
            return self.profiler.runcall(callback, *args, **callback_kwargs)

    def process_response(self, request, response):
        if settings.DEBUG and 'prof' in request.GET:
            self.profiler.create_stats()
            out = StringIO()
            old_stdout, sys.stdout = sys.stdout, out
            self.profiler.print_stats(1)
            sys.stdout = old_stdout
            response.content = '<pre>%s</pre>' % out.getvalue()
        return response

More like this

  1. Extended Profiling and Timing Middleware using cProfile by dstryke 1 year, 5 months ago
  2. Profiling Middleware w/sorting by petrilli 5 years, 9 months ago
  3. Profiling Middlware by udfalkso 7 years, 11 months ago
  4. Extended Profiling Middleware by hauser 7 years, 1 month ago
  5. Interactive Profiling Middleware by sfllaw 4 years, 8 months ago

Comments

mbi (on April 28, 2008):

It's lacking an 'import sys' somewhere, but works fine otherwise.

#

tuanopenid (on September 11, 2010):

Thank you!

#

Please login first before commenting.