PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/profile.py

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