PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/pstats.py

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