profiling.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # testing/profiling.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Profiling support for unit and performance tests.
  8. These are special purpose profiling methods which operate
  9. in a more fine-grained way than nose's profiling plugin.
  10. """
  11. import os
  12. import sys
  13. from .util import gc_collect
  14. from . import config
  15. import pstats
  16. import collections
  17. import contextlib
  18. try:
  19. import cProfile
  20. except ImportError:
  21. cProfile = None
  22. from ..util import jython, pypy, win32, update_wrapper
  23. _current_test = None
  24. # ProfileStatsFile instance, set up in plugin_base
  25. _profile_stats = None
  26. class ProfileStatsFile(object):
  27. """"Store per-platform/fn profiling results in a file.
  28. We're still targeting Py2.5, 2.4 on 0.7 with no dependencies,
  29. so no json lib :( need to roll something silly
  30. """
  31. def __init__(self, filename):
  32. self.force_write = (
  33. config.options is not None and
  34. config.options.force_write_profiles
  35. )
  36. self.write = self.force_write or (
  37. config.options is not None and
  38. config.options.write_profiles
  39. )
  40. self.fname = os.path.abspath(filename)
  41. self.short_fname = os.path.split(self.fname)[-1]
  42. self.data = collections.defaultdict(
  43. lambda: collections.defaultdict(dict))
  44. self._read()
  45. if self.write:
  46. # rewrite for the case where features changed,
  47. # etc.
  48. self._write()
  49. @property
  50. def platform_key(self):
  51. dbapi_key = config.db.name + "_" + config.db.driver
  52. # keep it at 2.7, 3.1, 3.2, etc. for now.
  53. py_version = '.'.join([str(v) for v in sys.version_info[0:2]])
  54. platform_tokens = [py_version]
  55. platform_tokens.append(dbapi_key)
  56. if jython:
  57. platform_tokens.append("jython")
  58. if pypy:
  59. platform_tokens.append("pypy")
  60. if win32:
  61. platform_tokens.append("win")
  62. platform_tokens.append(
  63. "nativeunicode"
  64. if config.db.dialect.convert_unicode
  65. else "dbapiunicode"
  66. )
  67. _has_cext = config.requirements._has_cextensions()
  68. platform_tokens.append(_has_cext and "cextensions" or "nocextensions")
  69. return "_".join(platform_tokens)
  70. def has_stats(self):
  71. test_key = _current_test
  72. return (
  73. test_key in self.data and
  74. self.platform_key in self.data[test_key]
  75. )
  76. def result(self, callcount):
  77. test_key = _current_test
  78. per_fn = self.data[test_key]
  79. per_platform = per_fn[self.platform_key]
  80. if 'counts' not in per_platform:
  81. per_platform['counts'] = counts = []
  82. else:
  83. counts = per_platform['counts']
  84. if 'current_count' not in per_platform:
  85. per_platform['current_count'] = current_count = 0
  86. else:
  87. current_count = per_platform['current_count']
  88. has_count = len(counts) > current_count
  89. if not has_count:
  90. counts.append(callcount)
  91. if self.write:
  92. self._write()
  93. result = None
  94. else:
  95. result = per_platform['lineno'], counts[current_count]
  96. per_platform['current_count'] += 1
  97. return result
  98. def replace(self, callcount):
  99. test_key = _current_test
  100. per_fn = self.data[test_key]
  101. per_platform = per_fn[self.platform_key]
  102. counts = per_platform['counts']
  103. current_count = per_platform['current_count']
  104. if current_count < len(counts):
  105. counts[current_count - 1] = callcount
  106. else:
  107. counts[-1] = callcount
  108. if self.write:
  109. self._write()
  110. def _header(self):
  111. return (
  112. "# %s\n"
  113. "# This file is written out on a per-environment basis.\n"
  114. "# For each test in aaa_profiling, the corresponding "
  115. "function and \n"
  116. "# environment is located within this file. "
  117. "If it doesn't exist,\n"
  118. "# the test is skipped.\n"
  119. "# If a callcount does exist, it is compared "
  120. "to what we received. \n"
  121. "# assertions are raised if the counts do not match.\n"
  122. "# \n"
  123. "# To add a new callcount test, apply the function_call_count \n"
  124. "# decorator and re-run the tests using the --write-profiles \n"
  125. "# option - this file will be rewritten including the new count.\n"
  126. "# \n"
  127. ) % (self.fname)
  128. def _read(self):
  129. try:
  130. profile_f = open(self.fname)
  131. except IOError:
  132. return
  133. for lineno, line in enumerate(profile_f):
  134. line = line.strip()
  135. if not line or line.startswith("#"):
  136. continue
  137. test_key, platform_key, counts = line.split()
  138. per_fn = self.data[test_key]
  139. per_platform = per_fn[platform_key]
  140. c = [int(count) for count in counts.split(",")]
  141. per_platform['counts'] = c
  142. per_platform['lineno'] = lineno + 1
  143. per_platform['current_count'] = 0
  144. profile_f.close()
  145. def _write(self):
  146. print(("Writing profile file %s" % self.fname))
  147. profile_f = open(self.fname, "w")
  148. profile_f.write(self._header())
  149. for test_key in sorted(self.data):
  150. per_fn = self.data[test_key]
  151. profile_f.write("\n# TEST: %s\n\n" % test_key)
  152. for platform_key in sorted(per_fn):
  153. per_platform = per_fn[platform_key]
  154. c = ",".join(str(count) for count in per_platform['counts'])
  155. profile_f.write("%s %s %s\n" % (test_key, platform_key, c))
  156. profile_f.close()
  157. def function_call_count(variance=0.05):
  158. """Assert a target for a test case's function call count.
  159. The main purpose of this assertion is to detect changes in
  160. callcounts for various functions - the actual number is not as important.
  161. Callcounts are stored in a file keyed to Python version and OS platform
  162. information. This file is generated automatically for new tests,
  163. and versioned so that unexpected changes in callcounts will be detected.
  164. """
  165. def decorate(fn):
  166. def wrap(*args, **kw):
  167. with count_functions(variance=variance):
  168. return fn(*args, **kw)
  169. return update_wrapper(wrap, fn)
  170. return decorate
  171. @contextlib.contextmanager
  172. def count_functions(variance=0.05):
  173. if cProfile is None:
  174. raise SkipTest("cProfile is not installed")
  175. if not _profile_stats.has_stats() and not _profile_stats.write:
  176. config.skip_test(
  177. "No profiling stats available on this "
  178. "platform for this function. Run tests with "
  179. "--write-profiles to add statistics to %s for "
  180. "this platform." % _profile_stats.short_fname)
  181. gc_collect()
  182. pr = cProfile.Profile()
  183. pr.enable()
  184. #began = time.time()
  185. yield
  186. #ended = time.time()
  187. pr.disable()
  188. #s = compat.StringIO()
  189. stats = pstats.Stats(pr, stream=sys.stdout)
  190. #timespent = ended - began
  191. callcount = stats.total_calls
  192. expected = _profile_stats.result(callcount)
  193. if expected is None:
  194. expected_count = None
  195. else:
  196. line_no, expected_count = expected
  197. print(("Pstats calls: %d Expected %s" % (
  198. callcount,
  199. expected_count
  200. )
  201. ))
  202. stats.sort_stats("cumulative")
  203. stats.print_stats()
  204. if expected_count:
  205. deviance = int(callcount * variance)
  206. failed = abs(callcount - expected_count) > deviance
  207. if failed or _profile_stats.force_write:
  208. if _profile_stats.write:
  209. _profile_stats.replace(callcount)
  210. else:
  211. raise AssertionError(
  212. "Adjusted function call count %s not within %s%% "
  213. "of expected %s, platform %s. Rerun with "
  214. "--write-profiles to "
  215. "regenerate this callcount."
  216. % (
  217. callcount, (variance * 100),
  218. expected_count, _profile_stats.platform_key))