profiling.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # testing/profiling.py
  2. # Copyright (C) 2005-2026 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: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. """Profiling support for unit and performance tests.
  9. These are special purpose profiling methods which operate
  10. in a more fine-grained way than nose's profiling plugin.
  11. """
  12. from __future__ import annotations
  13. import collections
  14. import contextlib
  15. import os
  16. import platform
  17. import pstats
  18. import re
  19. import sys
  20. from . import config
  21. from .util import gc_collect
  22. from ..util import freethreading
  23. from ..util import has_compiled_ext
  24. try:
  25. import cProfile
  26. except ImportError:
  27. cProfile = None
  28. _profile_stats = None
  29. """global ProfileStatsFileInstance.
  30. plugin_base assigns this at the start of all tests.
  31. """
  32. _current_test = None
  33. """String id of current test.
  34. plugin_base assigns this at the start of each test using
  35. _start_current_test.
  36. """
  37. def _start_current_test(id_):
  38. global _current_test
  39. _current_test = id_
  40. if _profile_stats.force_write:
  41. _profile_stats.reset_count()
  42. class ProfileStatsFile:
  43. """Store per-platform/fn profiling results in a file.
  44. There was no json module available when this was written, but now
  45. the file format which is very deterministically line oriented is kind of
  46. handy in any case for diffs and merges.
  47. """
  48. def __init__(self, filename, sort="cumulative", dump=None):
  49. self.force_write = (
  50. config.options is not None and config.options.force_write_profiles
  51. )
  52. self.write = self.force_write or (
  53. config.options is not None and config.options.write_profiles
  54. )
  55. self.fname = os.path.abspath(filename)
  56. self.short_fname = os.path.split(self.fname)[-1]
  57. self.data = collections.defaultdict(
  58. lambda: collections.defaultdict(dict)
  59. )
  60. self.dump = dump
  61. self.sort = sort
  62. self._read()
  63. if self.write:
  64. # rewrite for the case where features changed,
  65. # etc.
  66. self._write()
  67. @property
  68. def platform_key(self):
  69. dbapi_key = config.db.name + "_" + config.db.driver
  70. if config.db.dialect.is_async:
  71. dbapi_key += "_async"
  72. if config.db.name == "sqlite" and config.db.dialect._is_url_file_db(
  73. config.db.url
  74. ):
  75. dbapi_key += "_file"
  76. # keep it at 2.7, 3.1, 3.2, etc. for now.
  77. py_version = ".".join([str(v) for v in sys.version_info[0:2]])
  78. if freethreading:
  79. py_version += "t"
  80. platform_tokens = [
  81. platform.machine(),
  82. platform.system().lower(),
  83. platform.python_implementation().lower(),
  84. py_version,
  85. dbapi_key,
  86. ]
  87. platform_tokens.append("dbapiunicode")
  88. _has_cext = has_compiled_ext()
  89. platform_tokens.append(_has_cext and "cextensions" or "nocextensions")
  90. return "_".join(platform_tokens)
  91. def has_stats(self):
  92. test_key = _current_test
  93. return (
  94. test_key in self.data and self.platform_key in self.data[test_key]
  95. )
  96. def result(self, callcount):
  97. test_key = _current_test
  98. per_fn = self.data[test_key]
  99. per_platform = per_fn[self.platform_key]
  100. if "counts" not in per_platform:
  101. per_platform["counts"] = counts = []
  102. else:
  103. counts = per_platform["counts"]
  104. if "current_count" not in per_platform:
  105. per_platform["current_count"] = current_count = 0
  106. else:
  107. current_count = per_platform["current_count"]
  108. has_count = len(counts) > current_count
  109. if not has_count:
  110. counts.append(callcount)
  111. if self.write:
  112. self._write()
  113. result = None
  114. else:
  115. result = per_platform["lineno"], counts[current_count]
  116. per_platform["current_count"] += 1
  117. return result
  118. def reset_count(self):
  119. test_key = _current_test
  120. # since self.data is a defaultdict, don't access a key
  121. # if we don't know it's there first.
  122. if test_key not in self.data:
  123. return
  124. per_fn = self.data[test_key]
  125. if self.platform_key not in per_fn:
  126. return
  127. per_platform = per_fn[self.platform_key]
  128. if "counts" in per_platform:
  129. per_platform["counts"][:] = []
  130. def replace(self, callcount):
  131. test_key = _current_test
  132. per_fn = self.data[test_key]
  133. per_platform = per_fn[self.platform_key]
  134. counts = per_platform["counts"]
  135. current_count = per_platform["current_count"]
  136. if current_count < len(counts):
  137. counts[current_count - 1] = callcount
  138. else:
  139. counts[-1] = callcount
  140. if self.write:
  141. self._write()
  142. def _header(self):
  143. return (
  144. "# %s\n"
  145. "# This file is written out on a per-environment basis.\n"
  146. "# For each test in aaa_profiling, the corresponding "
  147. "function and \n"
  148. "# environment is located within this file. "
  149. "If it doesn't exist,\n"
  150. "# the test is skipped.\n"
  151. "# If a callcount does exist, it is compared "
  152. "to what we received. \n"
  153. "# assertions are raised if the counts do not match.\n"
  154. "# \n"
  155. "# To add a new callcount test, apply the function_call_count \n"
  156. "# decorator and re-run the tests using the --write-profiles \n"
  157. "# option - this file will be rewritten including the new count.\n"
  158. "# \n"
  159. ) % (self.fname)
  160. def _read(self):
  161. try:
  162. profile_f = open(self.fname)
  163. except OSError:
  164. return
  165. for lineno, line in enumerate(profile_f):
  166. line = line.strip()
  167. if not line or line.startswith("#"):
  168. continue
  169. test_key, platform_key, counts = line.split()
  170. per_fn = self.data[test_key]
  171. per_platform = per_fn[platform_key]
  172. c = [int(count) for count in counts.split(",")]
  173. per_platform["counts"] = c
  174. per_platform["lineno"] = lineno + 1
  175. per_platform["current_count"] = 0
  176. profile_f.close()
  177. def _write(self):
  178. print("Writing profile file %s" % self.fname)
  179. profile_f = open(self.fname, "w")
  180. profile_f.write(self._header())
  181. for test_key in sorted(self.data):
  182. per_fn = self.data[test_key]
  183. profile_f.write("\n# TEST: %s\n\n" % test_key)
  184. for platform_key in sorted(per_fn):
  185. per_platform = per_fn[platform_key]
  186. c = ",".join(str(count) for count in per_platform["counts"])
  187. profile_f.write("%s %s %s\n" % (test_key, platform_key, c))
  188. profile_f.close()
  189. def function_call_count(variance=0.05, times=1, warmup=0):
  190. """Assert a target for a test case's function call count.
  191. The main purpose of this assertion is to detect changes in
  192. callcounts for various functions - the actual number is not as important.
  193. Callcounts are stored in a file keyed to Python version and OS platform
  194. information. This file is generated automatically for new tests,
  195. and versioned so that unexpected changes in callcounts will be detected.
  196. """
  197. # use signature-rewriting decorator function so that pytest fixtures
  198. # still work on py27. In Py3, update_wrapper() alone is good enough,
  199. # likely due to the introduction of __signature__.
  200. from sqlalchemy.util import decorator
  201. @decorator
  202. def wrap(fn, *args, **kw):
  203. for warm in range(warmup):
  204. fn(*args, **kw)
  205. timerange = range(times)
  206. with count_functions(variance=variance):
  207. for time in timerange:
  208. rv = fn(*args, **kw)
  209. return rv
  210. return wrap
  211. @contextlib.contextmanager
  212. def count_functions(variance=0.05):
  213. if cProfile is None:
  214. raise config._skip_test_exception("cProfile is not installed")
  215. if not _profile_stats.has_stats() and not _profile_stats.write:
  216. config.skip_test(
  217. "No profiling stats available on this "
  218. "platform for this function. Run tests with "
  219. "--write-profiles to add statistics to %s for "
  220. "this platform." % _profile_stats.short_fname
  221. )
  222. gc_collect()
  223. pr = cProfile.Profile()
  224. pr.enable()
  225. # began = time.time()
  226. yield
  227. # ended = time.time()
  228. pr.disable()
  229. # s = StringIO()
  230. stats = pstats.Stats(pr, stream=sys.stdout)
  231. # timespent = ended - began
  232. callcount = stats.total_calls
  233. expected = _profile_stats.result(callcount)
  234. if expected is None:
  235. expected_count = None
  236. else:
  237. line_no, expected_count = expected
  238. print("Pstats calls: %d Expected %s" % (callcount, expected_count))
  239. stats.sort_stats(*re.split(r"[, ]", _profile_stats.sort))
  240. stats.print_stats()
  241. if _profile_stats.dump:
  242. base, ext = os.path.splitext(_profile_stats.dump)
  243. test_name = _current_test.split(".")[-1]
  244. dumpfile = "%s_%s%s" % (base, test_name, ext or ".profile")
  245. stats.dump_stats(dumpfile)
  246. print("Dumped stats to file %s" % dumpfile)
  247. # stats.print_callers()
  248. if _profile_stats.force_write:
  249. _profile_stats.replace(callcount)
  250. elif expected_count:
  251. deviance = int(callcount * variance)
  252. failed = abs(callcount - expected_count) > deviance
  253. if failed:
  254. if _profile_stats.write:
  255. _profile_stats.replace(callcount)
  256. else:
  257. raise AssertionError(
  258. "Adjusted function call count %s not within %s%% "
  259. "of expected %s, platform %s. Rerun with "
  260. "--write-profiles to "
  261. "regenerate this callcount."
  262. % (
  263. callcount,
  264. (variance * 100),
  265. expected_count,
  266. _profile_stats.platform_key,
  267. )
  268. )