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.

pstats.py 23KB

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