/Lib/profile.py

http://unladen-swallow.googlecode.com/ · Python · 619 lines · 378 code · 90 blank · 151 comment · 77 complexity · a1f60efe55b84022b9c3eab5c8dfa233 MD5 · raw file

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