PageRenderTime 61ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/profile.py

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