2

In Django, I am using the below middleware Cprofiler snippet /from http://djangosnippets.org/snippets/727/ )

How do I change what is used to sort it? If I want to use sort_stats() where does that go in the code?

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
user984003
  • 28,050
  • 64
  • 189
  • 285

2 Answers2

0

I think you are looking for the sort_stats function and it needs to go right before print_stats.

 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.sort_stats('name')
        self.profiler.print_stats(1)
        sys.stdout = old_stdout
        response.content = '<pre>%s</pre>' % out.getvalue()
    return response

Also take a look at this http://docs.python.org/2/library/profile.html

Siddharth Sarda
  • 486
  • 2
  • 7
0

sort_stats() cannot be used directly on the profiler. I found the solution here:

http://djangosnippets.org/snippets/1579/

user984003
  • 28,050
  • 64
  • 189
  • 285