profile.py 23 KB

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