Added debug_toolbar app to project.
[wolnelektury.git] / apps / debug_toolbar / panels / profiler.py
1 from debug_toolbar.panels import DebugPanel
2 try: import cProfile as profile
3 except ImportError: import profile
4 import pstats
5 from django.template.loader import render_to_string
6
7 class ProfilerDebugPanel(DebugPanel):
8     """
9     Panel that displays the time a response took with cProfile output.
10     """
11     name = 'Profiler'
12
13     def __init__(self, request):
14         super(ProfilerDebugPanel, self).__init__(request)
15
16     def process_response(self, request, response):
17         stats = pstats.Stats(self.profiler)
18         function_calls = []
19         for func in stats.strip_dirs().sort_stats(1).fcn_list:
20             current = []
21             if stats.stats[func][0] != stats.stats[func][1]:
22                 current.append('%d/%d' % (stats.stats[func][1], stats.stats[func][0]))
23             else:
24                 current.append(stats.stats[func][1])
25             current.append(stats.stats[func][2]*1000)
26             current.append(stats.stats[func][2]*1000/stats.stats[func][1])
27             current.append(stats.stats[func][3]*1000)
28             current.append(stats.stats[func][3]*1000/stats.stats[func][0])
29             current.append(pstats.func_std_string(func))
30             function_calls.append(current)
31         self.stats = stats
32         self.function_calls = function_calls
33         return response
34
35     def process_view(self, request, callback, callback_args, callback_kwargs):
36         self.callback = callback
37         self.profiler = profile.Profile()
38         return self.profiler.runcall(callback, request, *callback_args, **callback_kwargs)
39         
40     def title(self):
41         return 'View: %.2fms' % (float(self.stats.total_tt)*1000,)
42
43     def url(self):
44         return ''
45
46     def content(self):
47         context = {
48             'callback': self.callback.__name__,
49             'module': self.callback.__module__,
50             'stats': self.stats,
51             'function_calls': self.function_calls,
52         }
53         return render_to_string('debug_toolbar/panels/profiler.html', context)