profiler.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Profiler support
  4. #
  5. # Copyright 2012-2019 Michael Buesch <m@bues.ch>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. #from cms.cython_support cimport * #@cy
  22. from cms.exception import *
  23. from io import StringIO
  24. __all__ = [
  25. "Profiler",
  26. ]
  27. class Profiler(object):
  28. __slots__ = (
  29. "__profileModule",
  30. "__pstatsModule",
  31. "__profiler",
  32. "__enableCount",
  33. )
  34. def __init__(self):
  35. try:
  36. import cProfile as profileModule
  37. except ImportError:
  38. profileModule = None
  39. self.__profileModule = profileModule
  40. try:
  41. import pstats as pstatsModule
  42. except ImportError:
  43. pstatsModule = None
  44. self.__pstatsModule = pstatsModule
  45. if not self.__profileModule or\
  46. not self.__pstatsModule:
  47. raise CMSException(404, "Failed to load cProfile/pstats modules. "
  48. "Cannot enable profiling.")
  49. self.__profiler = self.__profileModule.Profile()
  50. self.__enableCount = 0
  51. def start(self):
  52. if self.__enableCount <= 0:
  53. self.__profiler.enable()
  54. self.__enableCount += 1
  55. def stop(self):
  56. self.__enableCount = max(self.__enableCount - 1, 0)
  57. if self.__enableCount <= 0:
  58. self.__profiler.disable()
  59. def getResult(self):
  60. sio = StringIO()
  61. ps = self.__pstatsModule.Stats(self.__profiler,
  62. stream=sio)
  63. ps.sort_stats("time")
  64. ps.print_stats()
  65. return sio.getvalue()