2012-11-26 24 views
2

在Django中,我使用下面的中間件Cprofiler片斷/從http://djangosnippets.org/snippets/727/cProfiler Django的中間件:排序統計

如何改變什麼來排序呢?如果我想使用sort_stats(),那麼代碼中的代碼是什麼?

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 

回答

0

我想你正在尋找sort_stats函數,它需要在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 

另外看看這個http://docs.python.org/2/library/profile.html

+0

這給出了一個錯誤:「個人資料」對象有沒有屬性‘sort_stats’」 – user984003