profile.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. 用于测量性能的中间件
  5. """
  6. # Original version taken from http://www.djangosnippets.org/snippets/186/
  7. # Original author: udfalkso
  8. # Modified by: Shwagroo Team and Gun.io
  9. import sys
  10. import os
  11. import re
  12. import hotshot, hotshot.stats
  13. import tempfile
  14. from six import StringIO
  15. from django.conf import settings
  16. words_re = re.compile(r'\s+')
  17. group_prefix_re = [
  18. re.compile("^.*/django/[^/]+"),
  19. re.compile("^(.*)/[^/]+$"), # extract module path
  20. re.compile(".*"), # catch strange entries
  21. ]
  22. class ProfileMiddleware(object):
  23. """
  24. Displays hotshot profiling for any view.
  25. http://yoursite.com/yourview/?prof
  26. Add the "prof" key to query string by appending ?prof (or &prof=)
  27. and you'll see the profiling results in your browser.
  28. It's set up to only be available in django's debug mode, is available for superuser otherwise,
  29. but you really shouldn't add this middleware to any production configuration.
  30. WARNING: It uses hotshot profiler which is not thread safe.
  31. """
  32. def process_request(self, request):
  33. if settings.DEBUG and 'prof' in request.GET:
  34. self.tmpfile = tempfile.mktemp()
  35. self.prof = hotshot.Profile(self.tmpfile)
  36. def process_view(self, request, callback, callback_args, callback_kwargs):
  37. if settings.DEBUG and 'prof' in request.GET:
  38. return self.prof.runcall(callback, request, *callback_args, **callback_kwargs)
  39. def get_group(self, file_):
  40. for g in group_prefix_re:
  41. name = g.findall(file_)
  42. if name:
  43. return name[0]
  44. def get_summary(self, results_dict, total):
  45. list_ = [(item[1], item[0]) for item in results_dict.items()]
  46. list_.sort(reverse = True)
  47. list_ = list_[:40]
  48. res = " tottime\n"
  49. for item in list_:
  50. res += "%4.1f%% %7.3f %s\n" % (100 * item[0] / total if total else 0, item[0], item[1])
  51. return res
  52. def summary_for_files(self, stats_str):
  53. stats_str = stats_str.split("\n")[5:]
  54. stats = {}
  55. groups = {}
  56. total = 0
  57. for s in stats_str:
  58. fields = words_re.split(s)
  59. if len(fields) == 7:
  60. time = float(fields[2])
  61. total += time
  62. file_ = fields[6].split(":")[0]
  63. if not file_ in stats:
  64. stats[file_] = 0
  65. stats[file_] += time
  66. group = self.get_group(file_)
  67. if not group in groups:
  68. groups[group] = 0
  69. groups[group] += time
  70. return "<pre>" + \
  71. " ---- By file ----\n\n" + self.get_summary(stats, total) + "\n" + \
  72. " ---- By group ---\n\n" + self.get_summary(groups, total) + \
  73. "</pre>"
  74. def process_response(self, request, response):
  75. if settings.DEBUG and 'prof' in request.GET:
  76. self.prof.close()
  77. out = StringIO()
  78. old_stdout = sys.stdout
  79. sys.stdout = out
  80. stats = hotshot.stats.load(self.tmpfile)
  81. stats.sort_stats('time', 'calls')
  82. stats.print_stats()
  83. sys.stdout = old_stdout
  84. stats_str = out.getvalue()
  85. if response and response.content and stats_str:
  86. response.content = "<pre>" + stats_str + "</pre>"
  87. response.content = "\n".join(response.content.split("\n")[:40])
  88. response.content += self.summary_for_files(stats_str)
  89. os.unlink(self.tmpfile)
  90. return response