pstats.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. """Class for printing reports on profiled python code."""
  2. # Class for printing reports on profiled python code. rev 1.0 4/1/94
  3. #
  4. # Based on prior profile module by Sjoerd Mullender...
  5. # which was hacked somewhat by: Guido van Rossum
  6. #
  7. # see profile.doc and profile.py for more info.
  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 os
  32. import time
  33. import marshal
  34. import re
  35. __all__ = ["Stats"]
  36. class Stats:
  37. """This class is used for creating reports from data generated by the
  38. Profile class. It is a "friend" of that class, and imports data either
  39. by direct access to members of Profile class, or by reading in a dictionary
  40. that was emitted (via marshal) from the Profile class.
  41. The big change from the previous Profiler (in terms of raw functionality)
  42. is that an "add()" method has been provided to combine Stats from
  43. several distinct profile runs. Both the constructor and the add()
  44. method now take arbitrarily many file names as arguments.
  45. All the print methods now take an argument that indicates how many lines
  46. to print. If the arg is a floating point number between 0 and 1.0, then
  47. it is taken as a decimal percentage of the available lines to be printed
  48. (e.g., .1 means print 10% of all available lines). If it is an integer,
  49. it is taken to mean the number of lines of data that you wish to have
  50. printed.
  51. The sort_stats() method now processes some additional options (i.e., in
  52. addition to the old -1, 0, 1, or 2). It takes an arbitrary number of quoted
  53. strings to select the sort order. For example sort_stats('time', 'name')
  54. sorts on the major key of "internal function time", and on the minor
  55. key of 'the name of the function'. Look at the two tables in sort_stats()
  56. and get_sort_arg_defs(self) for more examples.
  57. All methods now return "self", so you can string together commands like:
  58. Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
  59. print_stats(5).print_callers(5)
  60. """
  61. def __init__(self, *args):
  62. if not len(args):
  63. arg = None
  64. else:
  65. arg = args[0]
  66. args = args[1:]
  67. self.init(arg)
  68. self.add(*args)
  69. def init(self, arg):
  70. self.all_callees = None # calc only if needed
  71. self.files = []
  72. self.fcn_list = None
  73. self.total_tt = 0
  74. self.total_calls = 0
  75. self.prim_calls = 0
  76. self.max_name_len = 0
  77. self.top_level = {}
  78. self.stats = {}
  79. self.sort_arg_dict = {}
  80. self.load_stats(arg)
  81. trouble = 1
  82. try:
  83. self.get_top_level_stats()
  84. trouble = 0
  85. finally:
  86. if trouble:
  87. print "Invalid timing data",
  88. if self.files: print self.files[-1],
  89. print
  90. def load_stats(self, arg):
  91. if not arg: self.stats = {}
  92. elif type(arg) == type(""):
  93. f = open(arg, 'rb')
  94. self.stats = marshal.load(f)
  95. f.close()
  96. try:
  97. file_stats = os.stat(arg)
  98. arg = time.ctime(file_stats.st_mtime) + " " + arg
  99. except: # in case this is not unix
  100. pass
  101. self.files = [ arg ]
  102. elif hasattr(arg, 'create_stats'):
  103. arg.create_stats()
  104. self.stats = arg.stats
  105. arg.stats = {}
  106. if not self.stats:
  107. raise TypeError, "Cannot create or construct a %r object from '%r''" % (
  108. self.__class__, arg)
  109. return
  110. def get_top_level_stats(self):
  111. for func, (cc, nc, tt, ct, callers) in self.stats.items():
  112. self.total_calls += nc
  113. self.prim_calls += cc
  114. self.total_tt += tt
  115. if callers.has_key(("jprofile", 0, "profiler")):
  116. self.top_level[func] = None
  117. if len(func_std_string(func)) > self.max_name_len:
  118. self.max_name_len = len(func_std_string(func))
  119. def add(self, *arg_list):
  120. if not arg_list: return self
  121. if len(arg_list) > 1: self.add(*arg_list[1:])
  122. other = arg_list[0]
  123. if type(self) != type(other) or self.__class__ != other.__class__:
  124. other = Stats(other)
  125. self.files += other.files
  126. self.total_calls += other.total_calls
  127. self.prim_calls += other.prim_calls
  128. self.total_tt += other.total_tt
  129. for func in other.top_level:
  130. self.top_level[func] = None
  131. if self.max_name_len < other.max_name_len:
  132. self.max_name_len = other.max_name_len
  133. self.fcn_list = None
  134. for func, stat in other.stats.iteritems():
  135. if func in self.stats:
  136. old_func_stat = self.stats[func]
  137. else:
  138. old_func_stat = (0, 0, 0, 0, {},)
  139. self.stats[func] = add_func_stats(old_func_stat, stat)
  140. return self
  141. def dump_stats(self, filename):
  142. """Write the profile data to a file we know how to load back."""
  143. f = file(filename, 'wb')
  144. try:
  145. marshal.dump(self.stats, f)
  146. finally:
  147. f.close()
  148. # list the tuple indices and directions for sorting,
  149. # along with some printable description
  150. sort_arg_dict_default = {
  151. "calls" : (((1,-1), ), "call count"),
  152. "cumulative": (((3,-1), ), "cumulative time"),
  153. "file" : (((4, 1), ), "file name"),
  154. "line" : (((5, 1), ), "line number"),
  155. "module" : (((4, 1), ), "file name"),
  156. "name" : (((6, 1), ), "function name"),
  157. "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
  158. "pcalls" : (((0,-1), ), "call count"),
  159. "stdname" : (((7, 1), ), "standard name"),
  160. "time" : (((2,-1), ), "internal time"),
  161. }
  162. def get_sort_arg_defs(self):
  163. """Expand all abbreviations that are unique."""
  164. if not self.sort_arg_dict:
  165. self.sort_arg_dict = dict = {}
  166. bad_list = {}
  167. for word, tup in self.sort_arg_dict_default.iteritems():
  168. fragment = word
  169. while fragment:
  170. if not fragment:
  171. break
  172. if fragment in dict:
  173. bad_list[fragment] = 0
  174. break
  175. dict[fragment] = tup
  176. fragment = fragment[:-1]
  177. for word in bad_list:
  178. del dict[word]
  179. return self.sort_arg_dict
  180. def sort_stats(self, *field):
  181. if not field:
  182. self.fcn_list = 0
  183. return self
  184. if len(field) == 1 and type(field[0]) == type(1):
  185. # Be compatible with old profiler
  186. field = [ {-1: "stdname",
  187. 0:"calls",
  188. 1:"time",
  189. 2: "cumulative" } [ field[0] ] ]
  190. sort_arg_defs = self.get_sort_arg_defs()
  191. sort_tuple = ()
  192. self.sort_type = ""
  193. connector = ""
  194. for word in field:
  195. sort_tuple = sort_tuple + sort_arg_defs[word][0]
  196. self.sort_type += connector + sort_arg_defs[word][1]
  197. connector = ", "
  198. stats_list = []
  199. for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
  200. stats_list.append((cc, nc, tt, ct) + func +
  201. (func_std_string(func), func))
  202. stats_list.sort(TupleComp(sort_tuple).compare)
  203. self.fcn_list = fcn_list = []
  204. for tuple in stats_list:
  205. fcn_list.append(tuple[-1])
  206. return self
  207. def reverse_order(self):
  208. if self.fcn_list:
  209. self.fcn_list.reverse()
  210. return self
  211. def strip_dirs(self):
  212. oldstats = self.stats
  213. self.stats = newstats = {}
  214. max_name_len = 0
  215. for func, (cc, nc, tt, ct, callers) in oldstats.iteritems():
  216. newfunc = func_strip_path(func)
  217. if len(func_std_string(newfunc)) > max_name_len:
  218. max_name_len = len(func_std_string(newfunc))
  219. newcallers = {}
  220. for func2, caller in callers.iteritems():
  221. newcallers[func_strip_path(func2)] = caller
  222. if newfunc in newstats:
  223. newstats[newfunc] = add_func_stats(
  224. newstats[newfunc],
  225. (cc, nc, tt, ct, newcallers))
  226. else:
  227. newstats[newfunc] = (cc, nc, tt, ct, newcallers)
  228. old_top = self.top_level
  229. self.top_level = new_top = {}
  230. for func in old_top:
  231. new_top[func_strip_path(func)] = None
  232. self.max_name_len = max_name_len
  233. self.fcn_list = None
  234. self.all_callees = None
  235. return self
  236. def calc_callees(self):
  237. if self.all_callees: return
  238. self.all_callees = all_callees = {}
  239. for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
  240. if not func in all_callees:
  241. all_callees[func] = {}
  242. for func2, caller in callers.iteritems():
  243. if not func2 in all_callees:
  244. all_callees[func2] = {}
  245. all_callees[func2][func] = caller
  246. return
  247. #******************************************************************
  248. # The following functions support actual printing of reports
  249. #******************************************************************
  250. # Optional "amount" is either a line count, or a percentage of lines.
  251. def eval_print_amount(self, sel, list, msg):
  252. new_list = list
  253. if type(sel) == type(""):
  254. new_list = []
  255. for func in list:
  256. if re.search(sel, func_std_string(func)):
  257. new_list.append(func)
  258. else:
  259. count = len(list)
  260. if type(sel) == type(1.0) and 0.0 <= sel < 1.0:
  261. count = int(count * sel + .5)
  262. new_list = list[:count]
  263. elif type(sel) == type(1) and 0 <= sel < count:
  264. count = sel
  265. new_list = list[:count]
  266. if len(list) != len(new_list):
  267. msg = msg + " List reduced from %r to %r due to restriction <%r>\n" % (
  268. len(list), len(new_list), sel)
  269. return new_list, msg
  270. def get_print_list(self, sel_list):
  271. width = self.max_name_len
  272. if self.fcn_list:
  273. list = self.fcn_list[:]
  274. msg = " Ordered by: " + self.sort_type + '\n'
  275. else:
  276. list = self.stats.keys()
  277. msg = " Random listing order was used\n"
  278. for selection in sel_list:
  279. list, msg = self.eval_print_amount(selection, list, msg)
  280. count = len(list)
  281. if not list:
  282. return 0, list
  283. print msg
  284. if count < len(self.stats):
  285. width = 0
  286. for func in list:
  287. if len(func_std_string(func)) > width:
  288. width = len(func_std_string(func))
  289. return width+2, list
  290. def print_stats(self, *amount):
  291. for filename in self.files:
  292. print filename
  293. if self.files: print
  294. indent = ' ' * 8
  295. for func in self.top_level:
  296. print indent, func_get_function_name(func)
  297. print indent, self.total_calls, "function calls",
  298. if self.total_calls != self.prim_calls:
  299. print "(%d primitive calls)" % self.prim_calls,
  300. print "in %.3f CPU seconds" % self.total_tt
  301. print
  302. width, list = self.get_print_list(amount)
  303. if list:
  304. self.print_title()
  305. for func in list:
  306. self.print_line(func)
  307. print
  308. print
  309. return self
  310. def print_callees(self, *amount):
  311. width, list = self.get_print_list(amount)
  312. if list:
  313. self.calc_callees()
  314. self.print_call_heading(width, "called...")
  315. for func in list:
  316. if func in self.all_callees:
  317. self.print_call_line(width, func, self.all_callees[func])
  318. else:
  319. self.print_call_line(width, func, {})
  320. print
  321. print
  322. return self
  323. def print_callers(self, *amount):
  324. width, list = self.get_print_list(amount)
  325. if list:
  326. self.print_call_heading(width, "was called by...")
  327. for func in list:
  328. cc, nc, tt, ct, callers = self.stats[func]
  329. self.print_call_line(width, func, callers)
  330. print
  331. print
  332. return self
  333. def print_call_heading(self, name_size, column_title):
  334. print "Function ".ljust(name_size) + column_title
  335. def print_call_line(self, name_size, source, call_dict):
  336. print func_std_string(source).ljust(name_size),
  337. if not call_dict:
  338. print "--"
  339. return
  340. clist = call_dict.keys()
  341. clist.sort()
  342. name_size = name_size + 1
  343. indent = ""
  344. for func in clist:
  345. name = func_std_string(func)
  346. print indent*name_size + name + '(%r)' % (call_dict[func],), \
  347. f8(self.stats[func][3])
  348. indent = " "
  349. def print_title(self):
  350. print ' ncalls tottime percall cumtime percall', \
  351. 'filename:lineno(function)'
  352. def print_line(self, func): # hack : should print percentages
  353. cc, nc, tt, ct, callers = self.stats[func]
  354. c = str(nc)
  355. if nc != cc:
  356. c = c + '/' + str(cc)
  357. print c.rjust(9),
  358. print f8(tt),
  359. if nc == 0:
  360. print ' '*8,
  361. else:
  362. print f8(tt/nc),
  363. print f8(ct),
  364. if cc == 0:
  365. print ' '*8,
  366. else:
  367. print f8(ct/cc),
  368. print func_std_string(func)
  369. def ignore(self):
  370. # Deprecated since 1.5.1 -- see the docs.
  371. pass # has no return value, so use at end of line :-)
  372. class TupleComp:
  373. """This class provides a generic function for comparing any two tuples.
  374. Each instance records a list of tuple-indices (from most significant
  375. to least significant), and sort direction (ascending or decending) for
  376. each tuple-index. The compare functions can then be used as the function
  377. argument to the system sort() function when a list of tuples need to be
  378. sorted in the instances order."""
  379. def __init__(self, comp_select_list):
  380. self.comp_select_list = comp_select_list
  381. def compare (self, left, right):
  382. for index, direction in self.comp_select_list:
  383. l = left[index]
  384. r = right[index]
  385. if l < r:
  386. return -direction
  387. if l > r:
  388. return direction
  389. return 0
  390. #**************************************************************************
  391. # func_name is a triple (file:string, line:int, name:string)
  392. def func_strip_path(func_name):
  393. filename, line, name = func_name
  394. return os.path.basename(filename), line, name
  395. def func_get_function_name(func):
  396. return func[2]
  397. def func_std_string(func_name): # match what old profile produced
  398. return "%s:%d(%s)" % func_name
  399. #**************************************************************************
  400. # The following functions combine statists for pairs functions.
  401. # The bulk of the processing involves correctly handling "call" lists,
  402. # such as callers and callees.
  403. #**************************************************************************
  404. def add_func_stats(target, source):
  405. """Add together all the stats for two profile entries."""
  406. cc, nc, tt, ct, callers = source
  407. t_cc, t_nc, t_tt, t_ct, t_callers = target
  408. return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct,
  409. add_callers(t_callers, callers))
  410. def add_callers(target, source):
  411. """Combine two caller lists in a single list."""
  412. new_callers = {}
  413. for func, caller in target.iteritems():
  414. new_callers[func] = caller
  415. for func, caller in source.iteritems():
  416. if func in new_callers:
  417. new_callers[func] = caller + new_callers[func]
  418. else:
  419. new_callers[func] = caller
  420. return new_callers
  421. def count_calls(callers):
  422. """Sum the caller statistics to get total number of calls received."""
  423. nc = 0
  424. for calls in callers.itervalues():
  425. nc += calls
  426. return nc
  427. #**************************************************************************
  428. # The following functions support printing of reports
  429. #**************************************************************************
  430. def f8(x):
  431. return "%8.3f" % x
  432. #**************************************************************************
  433. # Statistics browser added by ESR, April 2001
  434. #**************************************************************************
  435. if __name__ == '__main__':
  436. import cmd
  437. try:
  438. import readline
  439. except ImportError:
  440. pass
  441. class ProfileBrowser(cmd.Cmd):
  442. def __init__(self, profile=None):
  443. cmd.Cmd.__init__(self)
  444. self.prompt = "% "
  445. if profile is not None:
  446. self.stats = Stats(profile)
  447. else:
  448. self.stats = None
  449. def generic(self, fn, line):
  450. args = line.split()
  451. processed = []
  452. for term in args:
  453. try:
  454. processed.append(int(term))
  455. continue
  456. except ValueError:
  457. pass
  458. try:
  459. frac = float(term)
  460. if frac > 1 or frac < 0:
  461. print "Fraction argument mus be in [0, 1]"
  462. continue
  463. processed.append(frac)
  464. continue
  465. except ValueError:
  466. pass
  467. processed.append(term)
  468. if self.stats:
  469. getattr(self.stats, fn)(*processed)
  470. else:
  471. print "No statistics object is loaded."
  472. return 0
  473. def generic_help(self):
  474. print "Arguments may be:"
  475. print "* An integer maximum number of entries to print."
  476. print "* A decimal fractional number between 0 and 1, controlling"
  477. print " what fraction of selected entries to print."
  478. print "* A regular expression; only entries with function names"
  479. print " that match it are printed."
  480. def do_add(self, line):
  481. self.stats.add(line)
  482. return 0
  483. def help_add(self):
  484. print "Add profile info from given file to current statistics object."
  485. def do_callees(self, line):
  486. return self.generic('print_callees', line)
  487. def help_callees(self):
  488. print "Print callees statistics from the current stat object."
  489. self.generic_help()
  490. def do_callers(self, line):
  491. return self.generic('print_callers', line)
  492. def help_callers(self):
  493. print "Print callers statistics from the current stat object."
  494. self.generic_help()
  495. def do_EOF(self, line):
  496. print ""
  497. return 1
  498. def help_EOF(self):
  499. print "Leave the profile brower."
  500. def do_quit(self, line):
  501. return 1
  502. def help_quit(self):
  503. print "Leave the profile brower."
  504. def do_read(self, line):
  505. if line:
  506. try:
  507. self.stats = Stats(line)
  508. except IOError, args:
  509. print args[1]
  510. return
  511. self.prompt = line + "% "
  512. elif len(self.prompt) > 2:
  513. line = self.prompt[-2:]
  514. else:
  515. print "No statistics object is current -- cannot reload."
  516. return 0
  517. def help_read(self):
  518. print "Read in profile data from a specified file."
  519. def do_reverse(self, line):
  520. self.stats.reverse_order()
  521. return 0
  522. def help_reverse(self):
  523. print "Reverse the sort order of the profiling report."
  524. def do_sort(self, line):
  525. abbrevs = self.stats.get_sort_arg_defs()
  526. if line and not filter(lambda x,a=abbrevs: x not in a,line.split()):
  527. self.stats.sort_stats(*line.split())
  528. else:
  529. print "Valid sort keys (unique prefixes are accepted):"
  530. for (key, value) in Stats.sort_arg_dict_default.iteritems():
  531. print "%s -- %s" % (key, value[1])
  532. return 0
  533. def help_sort(self):
  534. print "Sort profile data according to specified keys."
  535. print "(Typing `sort' without arguments lists valid keys.)"
  536. def complete_sort(self, text, *args):
  537. return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
  538. def do_stats(self, line):
  539. return self.generic('print_stats', line)
  540. def help_stats(self):
  541. print "Print statistics from the current stat object."
  542. self.generic_help()
  543. def do_strip(self, line):
  544. self.stats.strip_dirs()
  545. return 0
  546. def help_strip(self):
  547. print "Strip leading path information from filenames in the report."
  548. def postcmd(self, stop, line):
  549. if stop:
  550. return stop
  551. return None
  552. import sys
  553. print "Welcome to the profile statistics browser."
  554. if len(sys.argv) > 1:
  555. initprofile = sys.argv[1]
  556. else:
  557. initprofile = None
  558. try:
  559. ProfileBrowser(initprofile).cmdloop()
  560. print "Goodbye."
  561. except KeyboardInterrupt:
  562. pass
  563. # That's all, folks.