profile.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. #! /usr/bin/env python3
  2. #
  3. # Class for profiling python code. rev 1.0 6/2/94
  4. #
  5. # Written by James Roskind
  6. # Based on prior profile module by Sjoerd Mullender...
  7. # which was hacked somewhat by: Guido van Rossum
  8. """Class for profiling Python code."""
  9. # Copyright Disney Enterprises, Inc. All Rights Reserved.
  10. # Licensed to PSF under a Contributor Agreement
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  21. # either express or implied. See the License for the specific language
  22. # governing permissions and limitations under the License.
  23. import sys
  24. import time
  25. import marshal
  26. __all__ = ["run", "runctx", "Profile"]
  27. # Sample timer for use with
  28. #i_count = 0
  29. #def integer_timer():
  30. # global i_count
  31. # i_count = i_count + 1
  32. # return i_count
  33. #itimes = integer_timer # replace with C coded timer returning integers
  34. class _Utils:
  35. """Support class for utility functions which are shared by
  36. profile.py and cProfile.py modules.
  37. Not supposed to be used directly.
  38. """
  39. def __init__(self, profiler):
  40. self.profiler = profiler
  41. def run(self, statement, filename, sort):
  42. prof = self.profiler()
  43. try:
  44. prof.run(statement)
  45. except SystemExit:
  46. pass
  47. finally:
  48. self._show(prof, filename, sort)
  49. def runctx(self, statement, globals, locals, filename, sort):
  50. prof = self.profiler()
  51. try:
  52. prof.runctx(statement, globals, locals)
  53. except SystemExit:
  54. pass
  55. finally:
  56. self._show(prof, filename, sort)
  57. def _show(self, prof, filename, sort):
  58. if filename is not None:
  59. prof.dump_stats(filename)
  60. else:
  61. prof.print_stats(sort)
  62. #**************************************************************************
  63. # The following are the static member functions for the profiler class
  64. # Note that an instance of Profile() is *not* needed to call them.
  65. #**************************************************************************
  66. def run(statement, filename=None, sort=-1):
  67. """Run statement under profiler optionally saving results in filename
  68. This function takes a single argument that can be passed to the
  69. "exec" statement, and an optional file name. In all cases this
  70. routine attempts to "exec" its first argument and gather profiling
  71. statistics from the execution. If no file name is present, then this
  72. function automatically prints a simple profiling report, sorted by the
  73. standard name string (file/line/function-name) that is presented in
  74. each line.
  75. """
  76. return _Utils(Profile).run(statement, filename, sort)
  77. def runctx(statement, globals, locals, filename=None, sort=-1):
  78. """Run statement under profiler, supplying your own globals and locals,
  79. optionally saving results in filename.
  80. statement and filename have the same semantics as profile.run
  81. """
  82. return _Utils(Profile).runctx(statement, globals, locals, filename, sort)
  83. class Profile:
  84. """Profiler class.
  85. self.cur is always a tuple. Each such tuple corresponds to a stack
  86. frame that is currently active (self.cur[-2]). The following are the
  87. definitions of its members. We use this external "parallel stack" to
  88. avoid contaminating the program that we are profiling. (old profiler
  89. used to write into the frames local dictionary!!) Derived classes
  90. can change the definition of some entries, as long as they leave
  91. [-2:] intact (frame and previous tuple). In case an internal error is
  92. detected, the -3 element is used as the function name.
  93. [ 0] = Time that needs to be charged to the parent frame's function.
  94. It is used so that a function call will not have to access the
  95. timing data for the parent frame.
  96. [ 1] = Total time spent in this frame's function, excluding time in
  97. subfunctions (this latter is tallied in cur[2]).
  98. [ 2] = Total time spent in subfunctions, excluding time executing the
  99. frame's function (this latter is tallied in cur[1]).
  100. [-3] = Name of the function that corresponds to this frame.
  101. [-2] = Actual frame that we correspond to (used to sync exception handling).
  102. [-1] = Our parent 6-tuple (corresponds to frame.f_back).
  103. Timing data for each function is stored as a 5-tuple in the dictionary
  104. self.timings[]. The index is always the name stored in self.cur[-3].
  105. The following are the definitions of the members:
  106. [0] = The number of times this function was called, not counting direct
  107. or indirect recursion,
  108. [1] = Number of times this function appears on the stack, minus one
  109. [2] = Total time spent internal to this function
  110. [3] = Cumulative time that this function was present on the stack. In
  111. non-recursive functions, this is the total execution time from start
  112. to finish of each invocation of a function, including time spent in
  113. all subfunctions.
  114. [4] = A dictionary indicating for each function name, the number of times
  115. it was called by us.
  116. """
  117. bias = 0 # calibration constant
  118. def __init__(self, timer=None, bias=None):
  119. self.timings = {}
  120. self.cur = None
  121. self.cmd = ""
  122. self.c_func_name = ""
  123. if bias is None:
  124. bias = self.bias
  125. self.bias = bias # Materialize in local dict for lookup speed.
  126. if not timer:
  127. self.timer = self.get_time = time.process_time
  128. self.dispatcher = self.trace_dispatch_i
  129. else:
  130. self.timer = timer
  131. t = self.timer() # test out timer function
  132. try:
  133. length = len(t)
  134. except TypeError:
  135. self.get_time = timer
  136. self.dispatcher = self.trace_dispatch_i
  137. else:
  138. if length == 2:
  139. self.dispatcher = self.trace_dispatch
  140. else:
  141. self.dispatcher = self.trace_dispatch_l
  142. # This get_time() implementation needs to be defined
  143. # here to capture the passed-in timer in the parameter
  144. # list (for performance). Note that we can't assume
  145. # the timer() result contains two values in all
  146. # cases.
  147. def get_time_timer(timer=timer, sum=sum):
  148. return sum(timer())
  149. self.get_time = get_time_timer
  150. self.t = self.get_time()
  151. self.simulate_call('profiler')
  152. # Heavily optimized dispatch routine for time.process_time() timer
  153. def trace_dispatch(self, frame, event, arg):
  154. timer = self.timer
  155. t = timer()
  156. t = t[0] + t[1] - self.t - self.bias
  157. if event == "c_call":
  158. self.c_func_name = arg.__name__
  159. if self.dispatch[event](self, frame,t):
  160. t = timer()
  161. self.t = t[0] + t[1]
  162. else:
  163. r = timer()
  164. self.t = r[0] + r[1] - t # put back unrecorded delta
  165. # Dispatch routine for best timer program (return = scalar, fastest if
  166. # an integer but float works too -- and time.process_time() relies on that).
  167. def trace_dispatch_i(self, frame, event, arg):
  168. timer = self.timer
  169. t = timer() - self.t - self.bias
  170. if event == "c_call":
  171. self.c_func_name = arg.__name__
  172. if self.dispatch[event](self, frame, t):
  173. self.t = timer()
  174. else:
  175. self.t = timer() - t # put back unrecorded delta
  176. # Dispatch routine for macintosh (timer returns time in ticks of
  177. # 1/60th second)
  178. def trace_dispatch_mac(self, frame, event, arg):
  179. timer = self.timer
  180. t = timer()/60.0 - self.t - self.bias
  181. if event == "c_call":
  182. self.c_func_name = arg.__name__
  183. if self.dispatch[event](self, frame, t):
  184. self.t = timer()/60.0
  185. else:
  186. self.t = timer()/60.0 - t # put back unrecorded delta
  187. # SLOW generic dispatch routine for timer returning lists of numbers
  188. def trace_dispatch_l(self, frame, event, arg):
  189. get_time = self.get_time
  190. t = get_time() - self.t - self.bias
  191. if event == "c_call":
  192. self.c_func_name = arg.__name__
  193. if self.dispatch[event](self, frame, t):
  194. self.t = get_time()
  195. else:
  196. self.t = get_time() - t # put back unrecorded delta
  197. # In the event handlers, the first 3 elements of self.cur are unpacked
  198. # into vrbls w/ 3-letter names. The last two characters are meant to be
  199. # mnemonic:
  200. # _pt self.cur[0] "parent time" time to be charged to parent frame
  201. # _it self.cur[1] "internal time" time spent directly in the function
  202. # _et self.cur[2] "external time" time spent in subfunctions
  203. def trace_dispatch_exception(self, frame, t):
  204. rpt, rit, ret, rfn, rframe, rcur = self.cur
  205. if (rframe is not frame) and rcur:
  206. return self.trace_dispatch_return(rframe, t)
  207. self.cur = rpt, rit+t, ret, rfn, rframe, rcur
  208. return 1
  209. def trace_dispatch_call(self, frame, t):
  210. if self.cur and frame.f_back is not self.cur[-2]:
  211. rpt, rit, ret, rfn, rframe, rcur = self.cur
  212. if not isinstance(rframe, Profile.fake_frame):
  213. assert rframe.f_back is frame.f_back, ("Bad call", rfn,
  214. rframe, rframe.f_back,
  215. frame, frame.f_back)
  216. self.trace_dispatch_return(rframe, 0)
  217. assert (self.cur is None or \
  218. frame.f_back is self.cur[-2]), ("Bad call",
  219. self.cur[-3])
  220. fcode = frame.f_code
  221. fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
  222. self.cur = (t, 0, 0, fn, frame, self.cur)
  223. timings = self.timings
  224. if fn in timings:
  225. cc, ns, tt, ct, callers = timings[fn]
  226. timings[fn] = cc, ns + 1, tt, ct, callers
  227. else:
  228. timings[fn] = 0, 0, 0, 0, {}
  229. return 1
  230. def trace_dispatch_c_call (self, frame, t):
  231. fn = ("", 0, self.c_func_name)
  232. self.cur = (t, 0, 0, fn, frame, self.cur)
  233. timings = self.timings
  234. if fn in timings:
  235. cc, ns, tt, ct, callers = timings[fn]
  236. timings[fn] = cc, ns+1, tt, ct, callers
  237. else:
  238. timings[fn] = 0, 0, 0, 0, {}
  239. return 1
  240. def trace_dispatch_return(self, frame, t):
  241. if frame is not self.cur[-2]:
  242. assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3])
  243. self.trace_dispatch_return(self.cur[-2], 0)
  244. # Prefix "r" means part of the Returning or exiting frame.
  245. # Prefix "p" means part of the Previous or Parent or older frame.
  246. rpt, rit, ret, rfn, frame, rcur = self.cur
  247. rit = rit + t
  248. frame_total = rit + ret
  249. ppt, pit, pet, pfn, pframe, pcur = rcur
  250. self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur
  251. timings = self.timings
  252. cc, ns, tt, ct, callers = timings[rfn]
  253. if not ns:
  254. # This is the only occurrence of the function on the stack.
  255. # Else this is a (directly or indirectly) recursive call, and
  256. # its cumulative time will get updated when the topmost call to
  257. # it returns.
  258. ct = ct + frame_total
  259. cc = cc + 1
  260. if pfn in callers:
  261. callers[pfn] = callers[pfn] + 1 # hack: gather more
  262. # stats such as the amount of time added to ct courtesy
  263. # of this specific call, and the contribution to cc
  264. # courtesy of this call.
  265. else:
  266. callers[pfn] = 1
  267. timings[rfn] = cc, ns - 1, tt + rit, ct, callers
  268. return 1
  269. dispatch = {
  270. "call": trace_dispatch_call,
  271. "exception": trace_dispatch_exception,
  272. "return": trace_dispatch_return,
  273. "c_call": trace_dispatch_c_call,
  274. "c_exception": trace_dispatch_return, # the C function returned
  275. "c_return": trace_dispatch_return,
  276. }
  277. # The next few functions play with self.cmd. By carefully preloading
  278. # our parallel stack, we can force the profiled result to include
  279. # an arbitrary string as the name of the calling function.
  280. # We use self.cmd as that string, and the resulting stats look
  281. # very nice :-).
  282. def set_cmd(self, cmd):
  283. if self.cur[-1]: return # already set
  284. self.cmd = cmd
  285. self.simulate_call(cmd)
  286. class fake_code:
  287. def __init__(self, filename, line, name):
  288. self.co_filename = filename
  289. self.co_line = line
  290. self.co_name = name
  291. self.co_firstlineno = 0
  292. def __repr__(self):
  293. return repr((self.co_filename, self.co_line, self.co_name))
  294. class fake_frame:
  295. def __init__(self, code, prior):
  296. self.f_code = code
  297. self.f_back = prior
  298. def simulate_call(self, name):
  299. code = self.fake_code('profile', 0, name)
  300. if self.cur:
  301. pframe = self.cur[-2]
  302. else:
  303. pframe = None
  304. frame = self.fake_frame(code, pframe)
  305. self.dispatch['call'](self, frame, 0)
  306. # collect stats from pending stack, including getting final
  307. # timings for self.cmd frame.
  308. def simulate_cmd_complete(self):
  309. get_time = self.get_time
  310. t = get_time() - self.t
  311. while self.cur[-1]:
  312. # We *can* cause assertion errors here if
  313. # dispatch_trace_return checks for a frame match!
  314. self.dispatch['return'](self, self.cur[-2], t)
  315. t = 0
  316. self.t = get_time() - t
  317. def print_stats(self, sort=-1):
  318. import pstats
  319. pstats.Stats(self).strip_dirs().sort_stats(sort). \
  320. print_stats()
  321. def dump_stats(self, file):
  322. with open(file, 'wb') as f:
  323. self.create_stats()
  324. marshal.dump(self.stats, f)
  325. def create_stats(self):
  326. self.simulate_cmd_complete()
  327. self.snapshot_stats()
  328. def snapshot_stats(self):
  329. self.stats = {}
  330. for func, (cc, ns, tt, ct, callers) in self.timings.items():
  331. callers = callers.copy()
  332. nc = 0
  333. for callcnt in callers.values():
  334. nc += callcnt
  335. self.stats[func] = cc, nc, tt, ct, callers
  336. # The following two methods can be called by clients to use
  337. # a profiler to profile a statement, given as a string.
  338. def run(self, cmd):
  339. import __main__
  340. dict = __main__.__dict__
  341. return self.runctx(cmd, dict, dict)
  342. def runctx(self, cmd, globals, locals):
  343. self.set_cmd(cmd)
  344. sys.setprofile(self.dispatcher)
  345. try:
  346. exec(cmd, globals, locals)
  347. finally:
  348. sys.setprofile(None)
  349. return self
  350. # This method is more useful to profile a single function call.
  351. def runcall(self, func, /, *args, **kw):
  352. self.set_cmd(repr(func))
  353. sys.setprofile(self.dispatcher)
  354. try:
  355. return func(*args, **kw)
  356. finally:
  357. sys.setprofile(None)
  358. #******************************************************************
  359. # The following calculates the overhead for using a profiler. The
  360. # problem is that it takes a fair amount of time for the profiler
  361. # to stop the stopwatch (from the time it receives an event).
  362. # Similarly, there is a delay from the time that the profiler
  363. # re-starts the stopwatch before the user's code really gets to
  364. # continue. The following code tries to measure the difference on
  365. # a per-event basis.
  366. #
  367. # Note that this difference is only significant if there are a lot of
  368. # events, and relatively little user code per event. For example,
  369. # code with small functions will typically benefit from having the
  370. # profiler calibrated for the current platform. This *could* be
  371. # done on the fly during init() time, but it is not worth the
  372. # effort. Also note that if too large a value specified, then
  373. # execution time on some functions will actually appear as a
  374. # negative number. It is *normal* for some functions (with very
  375. # low call counts) to have such negative stats, even if the
  376. # calibration figure is "correct."
  377. #
  378. # One alternative to profile-time calibration adjustments (i.e.,
  379. # adding in the magic little delta during each event) is to track
  380. # more carefully the number of events (and cumulatively, the number
  381. # of events during sub functions) that are seen. If this were
  382. # done, then the arithmetic could be done after the fact (i.e., at
  383. # display time). Currently, we track only call/return events.
  384. # These values can be deduced by examining the callees and callers
  385. # vectors for each functions. Hence we *can* almost correct the
  386. # internal time figure at print time (note that we currently don't
  387. # track exception event processing counts). Unfortunately, there
  388. # is currently no similar information for cumulative sub-function
  389. # time. It would not be hard to "get all this info" at profiler
  390. # time. Specifically, we would have to extend the tuples to keep
  391. # counts of this in each frame, and then extend the defs of timing
  392. # tuples to include the significant two figures. I'm a bit fearful
  393. # that this additional feature will slow the heavily optimized
  394. # event/time ratio (i.e., the profiler would run slower, fur a very
  395. # low "value added" feature.)
  396. #**************************************************************
  397. def calibrate(self, m, verbose=0):
  398. if self.__class__ is not Profile:
  399. raise TypeError("Subclasses must override .calibrate().")
  400. saved_bias = self.bias
  401. self.bias = 0
  402. try:
  403. return self._calibrate_inner(m, verbose)
  404. finally:
  405. self.bias = saved_bias
  406. def _calibrate_inner(self, m, verbose):
  407. get_time = self.get_time
  408. # Set up a test case to be run with and without profiling. Include
  409. # lots of calls, because we're trying to quantify stopwatch overhead.
  410. # Do not raise any exceptions, though, because we want to know
  411. # exactly how many profile events are generated (one call event, +
  412. # one return event, per Python-level call).
  413. def f1(n):
  414. for i in range(n):
  415. x = 1
  416. def f(m, f1=f1):
  417. for i in range(m):
  418. f1(100)
  419. f(m) # warm up the cache
  420. # elapsed_noprofile <- time f(m) takes without profiling.
  421. t0 = get_time()
  422. f(m)
  423. t1 = get_time()
  424. elapsed_noprofile = t1 - t0
  425. if verbose:
  426. print("elapsed time without profiling =", elapsed_noprofile)
  427. # elapsed_profile <- time f(m) takes with profiling. The difference
  428. # is profiling overhead, only some of which the profiler subtracts
  429. # out on its own.
  430. p = Profile()
  431. t0 = get_time()
  432. p.runctx('f(m)', globals(), locals())
  433. t1 = get_time()
  434. elapsed_profile = t1 - t0
  435. if verbose:
  436. print("elapsed time with profiling =", elapsed_profile)
  437. # reported_time <- "CPU seconds" the profiler charged to f and f1.
  438. total_calls = 0.0
  439. reported_time = 0.0
  440. for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
  441. p.timings.items():
  442. if funcname in ("f", "f1"):
  443. total_calls += cc
  444. reported_time += tt
  445. if verbose:
  446. print("'CPU seconds' profiler reported =", reported_time)
  447. print("total # calls =", total_calls)
  448. if total_calls != m + 1:
  449. raise ValueError("internal error: total calls = %d" % total_calls)
  450. # reported_time - elapsed_noprofile = overhead the profiler wasn't
  451. # able to measure. Divide by twice the number of calls (since there
  452. # are two profiler events per call in this test) to get the hidden
  453. # overhead per event.
  454. mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
  455. if verbose:
  456. print("mean stopwatch overhead per profile event =", mean)
  457. return mean
  458. #****************************************************************************
  459. def main():
  460. import os
  461. from optparse import OptionParser
  462. usage = "profile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..."
  463. parser = OptionParser(usage=usage)
  464. parser.allow_interspersed_args = False
  465. parser.add_option('-o', '--outfile', dest="outfile",
  466. help="Save stats to <outfile>", default=None)
  467. parser.add_option('-m', dest="module", action="store_true",
  468. help="Profile a library module.", default=False)
  469. parser.add_option('-s', '--sort', dest="sort",
  470. help="Sort order when printing to stdout, based on pstats.Stats class",
  471. default=-1)
  472. if not sys.argv[1:]:
  473. parser.print_usage()
  474. sys.exit(2)
  475. (options, args) = parser.parse_args()
  476. sys.argv[:] = args
  477. # The script that we're profiling may chdir, so capture the absolute path
  478. # to the output file at startup.
  479. if options.outfile is not None:
  480. options.outfile = os.path.abspath(options.outfile)
  481. if len(args) > 0:
  482. if options.module:
  483. import runpy
  484. code = "run_module(modname, run_name='__main__')"
  485. globs = {
  486. 'run_module': runpy.run_module,
  487. 'modname': args[0]
  488. }
  489. else:
  490. progname = args[0]
  491. sys.path.insert(0, os.path.dirname(progname))
  492. with open(progname, 'rb') as fp:
  493. code = compile(fp.read(), progname, 'exec')
  494. globs = {
  495. '__file__': progname,
  496. '__name__': '__main__',
  497. '__package__': None,
  498. '__cached__': None,
  499. }
  500. try:
  501. runctx(code, globs, None, options.outfile, options.sort)
  502. except BrokenPipeError as exc:
  503. # Prevent "Exception ignored" during interpreter shutdown.
  504. sys.stdout = None
  505. sys.exit(exc.errno)
  506. else:
  507. parser.print_usage()
  508. return parser
  509. # When invoked as main program, invoke the profiler on a script
  510. if __name__ == '__main__':
  511. main()