You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

profile.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. __all__ = ["run","help","Profile"]
  38. # Sample timer for use with
  39. #i_count = 0
  40. #def integer_timer():
  41. # global i_count
  42. # i_count = i_count + 1
  43. # return i_count
  44. #itimes = integer_timer # replace with C coded timer returning integers
  45. #**************************************************************************
  46. # The following are the static member functions for the profiler class
  47. # Note that an instance of Profile() is *not* needed to call them.
  48. #**************************************************************************
  49. def run(statement, filename=None):
  50. """Run statement under profiler optionally saving results in filename
  51. This function takes a single argument that can be passed to the
  52. "exec" statement, and an optional file name. In all cases this
  53. routine attempts to "exec" its first argument and gather profiling
  54. statistics from the execution. If no file name is present, then this
  55. function automatically prints a simple profiling report, sorted by the
  56. standard name string (file/line/function-name) that is presented in
  57. each line.
  58. """
  59. prof = Profile()
  60. try:
  61. prof = prof.run(statement)
  62. except SystemExit:
  63. pass
  64. if filename is not None:
  65. prof.dump_stats(filename)
  66. else:
  67. return prof.print_stats()
  68. # print help
  69. def help():
  70. for dirname in sys.path:
  71. fullname = os.path.join(dirname, 'profile.doc')
  72. if os.path.exists(fullname):
  73. sts = os.system('${PAGER-more} '+fullname)
  74. if sts: print '*** Pager exit status:', sts
  75. break
  76. else:
  77. print 'Sorry, can\'t find the help file "profile.doc"',
  78. print 'along the Python search path'
  79. class Profile:
  80. """Profiler class.
  81. self.cur is always a tuple. Each such tuple corresponds to a stack
  82. frame that is currently active (self.cur[-2]). The following are the
  83. definitions of its members. We use this external "parallel stack" to
  84. avoid contaminating the program that we are profiling. (old profiler
  85. used to write into the frames local dictionary!!) Derived classes
  86. can change the definition of some entries, as long as they leave
  87. [-2:] intact.
  88. [ 0] = Time that needs to be charged to the parent frame's function.
  89. It is used so that a function call will not have to access the
  90. timing data for the parent frame.
  91. [ 1] = Total time spent in this frame's function, excluding time in
  92. subfunctions
  93. [ 2] = Cumulative time spent in this frame's function, including time in
  94. all subfunctions to this frame.
  95. [-3] = Name of the function that corresponds to this frame.
  96. [-2] = Actual frame that we correspond to (used to sync exception handling)
  97. [-1] = Our parent 6-tuple (corresponds to frame.f_back)
  98. Timing data for each function is stored as a 5-tuple in the dictionary
  99. self.timings[]. The index is always the name stored in self.cur[4].
  100. The following are the definitions of the members:
  101. [0] = The number of times this function was called, not counting direct
  102. or indirect recursion,
  103. [1] = Number of times this function appears on the stack, minus one
  104. [2] = Total time spent internal to this function
  105. [3] = Cumulative time that this function was present on the stack. In
  106. non-recursive functions, this is the total execution time from start
  107. to finish of each invocation of a function, including time spent in
  108. all subfunctions.
  109. [5] = A dictionary indicating for each function name, the number of times
  110. it was called by us.
  111. """
  112. def __init__(self, timer=None):
  113. self.timings = {}
  114. self.cur = None
  115. self.cmd = ""
  116. self.dispatch = { \
  117. 'call' : self.trace_dispatch_call, \
  118. 'return' : self.trace_dispatch_return, \
  119. 'exception': self.trace_dispatch_exception, \
  120. }
  121. if not timer:
  122. if os.name == 'mac':
  123. import MacOS
  124. self.timer = MacOS.GetTicks
  125. self.dispatcher = self.trace_dispatch_mac
  126. self.get_time = self.get_time_mac
  127. elif hasattr(time, 'clock'):
  128. self.timer = time.clock
  129. self.dispatcher = self.trace_dispatch_i
  130. elif hasattr(os, 'times'):
  131. self.timer = os.times
  132. self.dispatcher = self.trace_dispatch
  133. else:
  134. self.timer = time.time
  135. self.dispatcher = self.trace_dispatch_i
  136. else:
  137. self.timer = timer
  138. t = self.timer() # test out timer function
  139. try:
  140. if len(t) == 2:
  141. self.dispatcher = self.trace_dispatch
  142. else:
  143. self.dispatcher = self.trace_dispatch_l
  144. except TypeError:
  145. self.dispatcher = self.trace_dispatch_i
  146. self.t = self.get_time()
  147. self.simulate_call('profiler')
  148. def get_time(self): # slow simulation of method to acquire time
  149. t = self.timer()
  150. if type(t) == type(()) or type(t) == type([]):
  151. t = reduce(lambda x,y: x+y, t, 0)
  152. return t
  153. def get_time_mac(self):
  154. return self.timer()/60.0
  155. # Heavily optimized dispatch routine for os.times() timer
  156. def trace_dispatch(self, frame, event, arg):
  157. t = self.timer()
  158. t = t[0] + t[1] - self.t # No Calibration constant
  159. # t = t[0] + t[1] - self.t - .00053 # Calibration constant
  160. if self.dispatch[event](frame,t):
  161. t = self.timer()
  162. self.t = t[0] + t[1]
  163. else:
  164. r = self.timer()
  165. self.t = r[0] + r[1] - t # put back unrecorded delta
  166. return
  167. # Dispatch routine for best timer program (return = scalar integer)
  168. def trace_dispatch_i(self, frame, event, arg):
  169. t = self.timer() - self.t # - 1 # Integer calibration constant
  170. if self.dispatch[event](frame,t):
  171. self.t = self.timer()
  172. else:
  173. self.t = self.timer() - t # put back unrecorded delta
  174. return
  175. # Dispatch routine for macintosh (timer returns time in ticks of 1/60th second)
  176. def trace_dispatch_mac(self, frame, event, arg):
  177. t = self.timer()/60.0 - self.t # - 1 # Integer calibration constant
  178. if self.dispatch[event](frame,t):
  179. self.t = self.timer()/60.0
  180. else:
  181. self.t = self.timer()/60.0 - t # put back unrecorded delta
  182. return
  183. # SLOW generic dispatch routine for timer returning lists of numbers
  184. def trace_dispatch_l(self, frame, event, arg):
  185. t = self.get_time() - self.t
  186. if self.dispatch[event](frame,t):
  187. self.t = self.get_time()
  188. else:
  189. self.t = self.get_time()-t # put back unrecorded delta
  190. return
  191. def trace_dispatch_exception(self, frame, t):
  192. rt, rtt, rct, rfn, rframe, rcur = self.cur
  193. if (not rframe is frame) and rcur:
  194. return self.trace_dispatch_return(rframe, t)
  195. return 0
  196. def trace_dispatch_call(self, frame, t):
  197. fcode = frame.f_code
  198. fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
  199. self.cur = (t, 0, 0, fn, frame, self.cur)
  200. if self.timings.has_key(fn):
  201. cc, ns, tt, ct, callers = self.timings[fn]
  202. self.timings[fn] = cc, ns + 1, tt, ct, callers
  203. else:
  204. self.timings[fn] = 0, 0, 0, 0, {}
  205. return 1
  206. def trace_dispatch_return(self, frame, t):
  207. # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
  208. # Prefix "r" means part of the Returning or exiting frame
  209. # Prefix "p" means part of the Previous or older frame
  210. rt, rtt, rct, rfn, frame, rcur = self.cur
  211. rtt = rtt + t
  212. sft = rtt + rct
  213. pt, ptt, pct, pfn, pframe, pcur = rcur
  214. self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  215. cc, ns, tt, ct, callers = self.timings[rfn]
  216. if not ns:
  217. ct = ct + sft
  218. cc = cc + 1
  219. if callers.has_key(pfn):
  220. callers[pfn] = callers[pfn] + 1 # hack: gather more
  221. # stats such as the amount of time added to ct courtesy
  222. # of this specific call, and the contribution to cc
  223. # courtesy of this call.
  224. else:
  225. callers[pfn] = 1
  226. self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
  227. return 1
  228. # The next few function play with self.cmd. By carefully preloading
  229. # our parallel stack, we can force the profiled result to include
  230. # an arbitrary string as the name of the calling function.
  231. # We use self.cmd as that string, and the resulting stats look
  232. # very nice :-).
  233. def set_cmd(self, cmd):
  234. if self.cur[-1]: return # already set
  235. self.cmd = cmd
  236. self.simulate_call(cmd)
  237. class fake_code:
  238. def __init__(self, filename, line, name):
  239. self.co_filename = filename
  240. self.co_line = line
  241. self.co_name = name
  242. self.co_firstlineno = 0
  243. def __repr__(self):
  244. return repr((self.co_filename, self.co_line, self.co_name))
  245. class fake_frame:
  246. def __init__(self, code, prior):
  247. self.f_code = code
  248. self.f_back = prior
  249. def simulate_call(self, name):
  250. code = self.fake_code('profile', 0, name)
  251. if self.cur:
  252. pframe = self.cur[-2]
  253. else:
  254. pframe = None
  255. frame = self.fake_frame(code, pframe)
  256. a = self.dispatch['call'](frame, 0)
  257. return
  258. # collect stats from pending stack, including getting final
  259. # timings for self.cmd frame.
  260. def simulate_cmd_complete(self):
  261. t = self.get_time() - self.t
  262. while self.cur[-1]:
  263. # We *can* cause assertion errors here if
  264. # dispatch_trace_return checks for a frame match!
  265. a = self.dispatch['return'](self.cur[-2], t)
  266. t = 0
  267. self.t = self.get_time() - t
  268. def print_stats(self):
  269. import pstats
  270. pstats.Stats(self).strip_dirs().sort_stats(-1). \
  271. print_stats()
  272. def dump_stats(self, file):
  273. f = open(file, 'wb')
  274. self.create_stats()
  275. marshal.dump(self.stats, f)
  276. f.close()
  277. def create_stats(self):
  278. self.simulate_cmd_complete()
  279. self.snapshot_stats()
  280. def snapshot_stats(self):
  281. self.stats = {}
  282. for func in self.timings.keys():
  283. cc, ns, tt, ct, callers = self.timings[func]
  284. callers = callers.copy()
  285. nc = 0
  286. for func_caller in callers.keys():
  287. nc = nc + callers[func_caller]
  288. self.stats[func] = cc, nc, tt, ct, callers
  289. # The following two methods can be called by clients to use
  290. # a profiler to profile a statement, given as a string.
  291. def run(self, cmd):
  292. import __main__
  293. dict = __main__.__dict__
  294. return self.runctx(cmd, dict, dict)
  295. def runctx(self, cmd, globals, locals):
  296. self.set_cmd(cmd)
  297. sys.setprofile(self.dispatcher)
  298. try:
  299. exec cmd in globals, locals
  300. finally:
  301. sys.setprofile(None)
  302. return self
  303. # This method is more useful to profile a single function call.
  304. def runcall(self, func, *args):
  305. self.set_cmd(`func`)
  306. sys.setprofile(self.dispatcher)
  307. try:
  308. return apply(func, args)
  309. finally:
  310. sys.setprofile(None)
  311. #******************************************************************
  312. # The following calculates the overhead for using a profiler. The
  313. # problem is that it takes a fair amount of time for the profiler
  314. # to stop the stopwatch (from the time it receives an event).
  315. # Similarly, there is a delay from the time that the profiler
  316. # re-starts the stopwatch before the user's code really gets to
  317. # continue. The following code tries to measure the difference on
  318. # a per-event basis. The result can the be placed in the
  319. # Profile.dispatch_event() routine for the given platform. Note
  320. # that this difference is only significant if there are a lot of
  321. # events, and relatively little user code per event. For example,
  322. # code with small functions will typically benefit from having the
  323. # profiler calibrated for the current platform. This *could* be
  324. # done on the fly during init() time, but it is not worth the
  325. # effort. Also note that if too large a value specified, then
  326. # execution time on some functions will actually appear as a
  327. # negative number. It is *normal* for some functions (with very
  328. # low call counts) to have such negative stats, even if the
  329. # calibration figure is "correct."
  330. #
  331. # One alternative to profile-time calibration adjustments (i.e.,
  332. # adding in the magic little delta during each event) is to track
  333. # more carefully the number of events (and cumulatively, the number
  334. # of events during sub functions) that are seen. If this were
  335. # done, then the arithmetic could be done after the fact (i.e., at
  336. # display time). Currently, we track only call/return events.
  337. # These values can be deduced by examining the callees and callers
  338. # vectors for each functions. Hence we *can* almost correct the
  339. # internal time figure at print time (note that we currently don't
  340. # track exception event processing counts). Unfortunately, there
  341. # is currently no similar information for cumulative sub-function
  342. # time. It would not be hard to "get all this info" at profiler
  343. # time. Specifically, we would have to extend the tuples to keep
  344. # counts of this in each frame, and then extend the defs of timing
  345. # tuples to include the significant two figures. I'm a bit fearful
  346. # that this additional feature will slow the heavily optimized
  347. # event/time ratio (i.e., the profiler would run slower, fur a very
  348. # low "value added" feature.)
  349. #
  350. # Plugging in the calibration constant doesn't slow down the
  351. # profiler very much, and the accuracy goes way up.
  352. #**************************************************************
  353. def calibrate(self, m):
  354. # Modified by Tim Peters
  355. n = m
  356. s = self.get_time()
  357. while n:
  358. self.simple()
  359. n = n - 1
  360. f = self.get_time()
  361. my_simple = f - s
  362. #print "Simple =", my_simple,
  363. n = m
  364. s = self.get_time()
  365. while n:
  366. self.instrumented()
  367. n = n - 1
  368. f = self.get_time()
  369. my_inst = f - s
  370. # print "Instrumented =", my_inst
  371. avg_cost = (my_inst - my_simple)/m
  372. #print "Delta/call =", avg_cost, "(profiler fixup constant)"
  373. return avg_cost
  374. # simulate a program with no profiler activity
  375. def simple(self):
  376. a = 1
  377. pass
  378. # simulate a program with call/return event processing
  379. def instrumented(self):
  380. a = 1
  381. self.profiler_simulation(a, a, a)
  382. # simulate an event processing activity (from user's perspective)
  383. def profiler_simulation(self, x, y, z):
  384. t = self.timer()
  385. ## t = t[0] + t[1]
  386. self.ut = t
  387. class OldProfile(Profile):
  388. """A derived profiler that simulates the old style profile, providing
  389. errant results on recursive functions. The reason for the usefulness of
  390. this profiler is that it runs faster (i.e., less overhead). It still
  391. creates all the caller stats, and is quite useful when there is *no*
  392. recursion in the user's code.
  393. This code also shows how easy it is to create a modified profiler.
  394. """
  395. def trace_dispatch_exception(self, frame, t):
  396. rt, rtt, rct, rfn, rframe, rcur = self.cur
  397. if rcur and not rframe is frame:
  398. return self.trace_dispatch_return(rframe, t)
  399. return 0
  400. def trace_dispatch_call(self, frame, t):
  401. fn = `frame.f_code`
  402. self.cur = (t, 0, 0, fn, frame, self.cur)
  403. if self.timings.has_key(fn):
  404. tt, ct, callers = self.timings[fn]
  405. self.timings[fn] = tt, ct, callers
  406. else:
  407. self.timings[fn] = 0, 0, {}
  408. return 1
  409. def trace_dispatch_return(self, frame, t):
  410. rt, rtt, rct, rfn, frame, rcur = self.cur
  411. rtt = rtt + t
  412. sft = rtt + rct
  413. pt, ptt, pct, pfn, pframe, pcur = rcur
  414. self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  415. tt, ct, callers = self.timings[rfn]
  416. if callers.has_key(pfn):
  417. callers[pfn] = callers[pfn] + 1
  418. else:
  419. callers[pfn] = 1
  420. self.timings[rfn] = tt+rtt, ct + sft, callers
  421. return 1
  422. def snapshot_stats(self):
  423. self.stats = {}
  424. for func in self.timings.keys():
  425. tt, ct, callers = self.timings[func]
  426. callers = callers.copy()
  427. nc = 0
  428. for func_caller in callers.keys():
  429. nc = nc + callers[func_caller]
  430. self.stats[func] = nc, nc, tt, ct, callers
  431. class HotProfile(Profile):
  432. """The fastest derived profile example. It does not calculate
  433. caller-callee relationships, and does not calculate cumulative
  434. time under a function. It only calculates time spent in a
  435. function, so it runs very quickly due to its very low overhead.
  436. """
  437. def trace_dispatch_exception(self, frame, t):
  438. rt, rtt, rfn, rframe, rcur = self.cur
  439. if rcur and not rframe is frame:
  440. return self.trace_dispatch_return(rframe, t)
  441. return 0
  442. def trace_dispatch_call(self, frame, t):
  443. self.cur = (t, 0, frame, self.cur)
  444. return 1
  445. def trace_dispatch_return(self, frame, t):
  446. rt, rtt, frame, rcur = self.cur
  447. rfn = `frame.f_code`
  448. pt, ptt, pframe, pcur = rcur
  449. self.cur = pt, ptt+rt, pframe, pcur
  450. if self.timings.has_key(rfn):
  451. nc, tt = self.timings[rfn]
  452. self.timings[rfn] = nc + 1, rt + rtt + tt
  453. else:
  454. self.timings[rfn] = 1, rt + rtt
  455. return 1
  456. def snapshot_stats(self):
  457. self.stats = {}
  458. for func in self.timings.keys():
  459. nc, tt = self.timings[func]
  460. self.stats[func] = nc, nc, tt, 0, {}
  461. #****************************************************************************
  462. def Stats(*args):
  463. print 'Report generating functions are in the "pstats" module\a'
  464. # When invoked as main program, invoke the profiler on a script
  465. if __name__ == '__main__':
  466. import sys
  467. import os
  468. if not sys.argv[1:]:
  469. print "usage: profile.py scriptfile [arg] ..."
  470. sys.exit(2)
  471. filename = sys.argv[1] # Get script filename
  472. del sys.argv[0] # Hide "profile.py" from argument list
  473. # Insert script directory in front of module search path
  474. sys.path.insert(0, os.path.dirname(filename))
  475. run('execfile(' + `filename` + ')')