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

/lib-python/2/pstats.py

https://bitbucket.org/kcr/pypy
Python | 701 lines | 676 code | 6 blank | 19 comment | 2 complexity | 5bc9ed1bbd007b0cb02cedec1f93d6ba MD5 | raw file
Possible License(s): Apache-2.0
  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 explictly 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. "cumulative": (((3,-1), ), "cumulative time"),
  156. "file" : (((4, 1), ), "file name"),
  157. "line" : (((5, 1), ), "line number"),
  158. "module" : (((4, 1), ), "file name"),
  159. "name" : (((6, 1), ), "function name"),
  160. "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
  161. "pcalls" : (((0,-1), ), "call count"),
  162. "stdname" : (((7, 1), ), "standard name"),
  163. "time" : (((2,-1), ), "internal time"),
  164. }
  165. def get_sort_arg_defs(self):
  166. """Expand all abbreviations that are unique."""
  167. if not self.sort_arg_dict:
  168. self.sort_arg_dict = dict = {}
  169. bad_list = {}
  170. for word, tup in self.sort_arg_dict_default.iteritems():
  171. fragment = word
  172. while fragment:
  173. if not fragment:
  174. break
  175. if fragment in dict:
  176. bad_list[fragment] = 0
  177. break
  178. dict[fragment] = tup
  179. fragment = fragment[:-1]
  180. for word in bad_list:
  181. del dict[word]
  182. return self.sort_arg_dict
  183. def sort_stats(self, *field):
  184. if not field:
  185. self.fcn_list = 0
  186. return self
  187. if len(field) == 1 and isinstance(field[0], (int, long)):
  188. # Be compatible with old profiler
  189. field = [ {-1: "stdname",
  190. 0: "calls",
  191. 1: "time",
  192. 2: "cumulative"}[field[0]] ]
  193. sort_arg_defs = self.get_sort_arg_defs()
  194. sort_tuple = ()
  195. self.sort_type = ""
  196. connector = ""
  197. for word in field:
  198. sort_tuple = sort_tuple + sort_arg_defs[word][0]
  199. self.sort_type += connector + sort_arg_defs[word][1]
  200. connector = ", "
  201. stats_list = []
  202. for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
  203. stats_list.append((cc, nc, tt, ct) + func +
  204. (func_std_string(func), func))
  205. stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))
  206. self.fcn_list = fcn_list = []
  207. for tuple in stats_list:
  208. fcn_list.append(tuple[-1])
  209. return self
  210. def reverse_order(self):
  211. if self.fcn_list:
  212. self.fcn_list.reverse()
  213. return self
  214. def strip_dirs(self):
  215. oldstats = self.stats
  216. self.stats = newstats = {}
  217. max_name_len = 0
  218. for func, (cc, nc, tt, ct, callers) in oldstats.iteritems():
  219. newfunc = func_strip_path(func)
  220. if len(func_std_string(newfunc)) > max_name_len:
  221. max_name_len = len(func_std_string(newfunc))
  222. newcallers = {}
  223. for func2, caller in callers.iteritems():
  224. newcallers[func_strip_path(func2)] = caller
  225. if newfunc in newstats:
  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:
  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, (cc, nc, tt, ct, callers) in self.stats.iteritems():
  243. if not func in all_callees:
  244. all_callees[func] = {}
  245. for func2, caller in callers.iteritems():
  246. if not func2 in all_callees:
  247. all_callees[func2] = {}
  248. all_callees[func2][func] = caller
  249. return
  250. #******************************************************************
  251. # The following functions support actual printing of reports
  252. #******************************************************************
  253. # Optional "amount" is either a line count, or a percentage of lines.
  254. def eval_print_amount(self, sel, list, msg):
  255. new_list = list
  256. if isinstance(sel, basestring):
  257. try:
  258. rex = re.compile(sel)
  259. except re.error:
  260. msg += " <Invalid regular expression %r>\n" % sel
  261. return new_list, msg
  262. new_list = []
  263. for func in list:
  264. if rex.search(func_std_string(func)):
  265. new_list.append(func)
  266. else:
  267. count = len(list)
  268. if isinstance(sel, float) and 0.0 <= sel < 1.0:
  269. count = int(count * sel + .5)
  270. new_list = list[:count]
  271. elif isinstance(sel, (int, long)) and 0 <= sel < count:
  272. count = sel
  273. new_list = list[:count]
  274. if len(list) != len(new_list):
  275. msg += " List reduced from %r to %r due to restriction <%r>\n" % (
  276. len(list), len(new_list), sel)
  277. return new_list, msg
  278. def get_print_list(self, sel_list):
  279. width = self.max_name_len
  280. if self.fcn_list:
  281. stat_list = self.fcn_list[:]
  282. msg = " Ordered by: " + self.sort_type + '\n'
  283. else:
  284. stat_list = self.stats.keys()
  285. msg = " Random listing order was used\n"
  286. for selection in sel_list:
  287. stat_list, msg = self.eval_print_amount(selection, stat_list, msg)
  288. count = len(stat_list)
  289. if not stat_list:
  290. return 0, stat_list
  291. print >> self.stream, msg
  292. if count < len(self.stats):
  293. width = 0
  294. for func in stat_list:
  295. if len(func_std_string(func)) > width:
  296. width = len(func_std_string(func))
  297. return width+2, stat_list
  298. def print_stats(self, *amount):
  299. for filename in self.files:
  300. print >> self.stream, filename
  301. if self.files: print >> self.stream
  302. indent = ' ' * 8
  303. for func in self.top_level:
  304. print >> self.stream, indent, func_get_function_name(func)
  305. print >> self.stream, indent, self.total_calls, "function calls",
  306. if self.total_calls != self.prim_calls:
  307. print >> self.stream, "(%d primitive calls)" % self.prim_calls,
  308. print >> self.stream, "in %.3f seconds" % self.total_tt
  309. print >> self.stream
  310. width, list = self.get_print_list(amount)
  311. if list:
  312. self.print_title()
  313. for func in list:
  314. self.print_line(func)
  315. print >> self.stream
  316. print >> self.stream
  317. return self
  318. def print_callees(self, *amount):
  319. width, list = self.get_print_list(amount)
  320. if list:
  321. self.calc_callees()
  322. self.print_call_heading(width, "called...")
  323. for func in list:
  324. if func in self.all_callees:
  325. self.print_call_line(width, func, self.all_callees[func])
  326. else:
  327. self.print_call_line(width, func, {})
  328. print >> self.stream
  329. print >> self.stream
  330. return self
  331. def print_callers(self, *amount):
  332. width, list = self.get_print_list(amount)
  333. if list:
  334. self.print_call_heading(width, "was called by...")
  335. for func in list:
  336. cc, nc, tt, ct, callers = self.stats[func]
  337. self.print_call_line(width, func, callers, "<-")
  338. print >> self.stream
  339. print >> self.stream
  340. return self
  341. def print_call_heading(self, name_size, column_title):
  342. print >> self.stream, "Function ".ljust(name_size) + column_title
  343. # print sub-header only if we have new-style callers
  344. subheader = False
  345. for cc, nc, tt, ct, callers in self.stats.itervalues():
  346. if callers:
  347. value = callers.itervalues().next()
  348. subheader = isinstance(value, tuple)
  349. break
  350. if subheader:
  351. print >> self.stream, " "*name_size + " ncalls tottime cumtime"
  352. def print_call_line(self, name_size, source, call_dict, arrow="->"):
  353. print >> self.stream, func_std_string(source).ljust(name_size) + arrow,
  354. if not call_dict:
  355. print >> self.stream
  356. return
  357. clist = call_dict.keys()
  358. clist.sort()
  359. indent = ""
  360. for func in clist:
  361. name = func_std_string(func)
  362. value = call_dict[func]
  363. if isinstance(value, tuple):
  364. nc, cc, tt, ct = value
  365. if nc != cc:
  366. substats = '%d/%d' % (nc, cc)
  367. else:
  368. substats = '%d' % (nc,)
  369. substats = '%s %s %s %s' % (substats.rjust(7+2*len(indent)),
  370. f8(tt), f8(ct), name)
  371. left_width = name_size + 1
  372. else:
  373. substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
  374. left_width = name_size + 3
  375. print >> self.stream, indent*left_width + substats
  376. indent = " "
  377. def print_title(self):
  378. print >> self.stream, ' ncalls tottime percall cumtime percall',
  379. print >> self.stream, 'filename:lineno(function)'
  380. def print_line(self, func): # hack : should print percentages
  381. cc, nc, tt, ct, callers = self.stats[func]
  382. c = str(nc)
  383. if nc != cc:
  384. c = c + '/' + str(cc)
  385. print >> self.stream, c.rjust(9),
  386. print >> self.stream, f8(tt),
  387. if nc == 0:
  388. print >> self.stream, ' '*8,
  389. else:
  390. print >> self.stream, f8(float(tt)/nc),
  391. print >> self.stream, f8(ct),
  392. if cc == 0:
  393. print >> self.stream, ' '*8,
  394. else:
  395. print >> self.stream, f8(float(ct)/cc),
  396. print >> self.stream, func_std_string(func)
  397. class TupleComp:
  398. """This class provides a generic function for comparing any two tuples.
  399. Each instance records a list of tuple-indices (from most significant
  400. to least significant), and sort direction (ascending or decending) for
  401. each tuple-index. The compare functions can then be used as the function
  402. argument to the system sort() function when a list of tuples need to be
  403. sorted in the instances order."""
  404. def __init__(self, comp_select_list):
  405. self.comp_select_list = comp_select_list
  406. def compare (self, left, right):
  407. for index, direction in self.comp_select_list:
  408. l = left[index]
  409. r = right[index]
  410. if l < r:
  411. return -direction
  412. if l > r:
  413. return direction
  414. return 0
  415. #**************************************************************************
  416. # func_name is a triple (file:string, line:int, name:string)
  417. def func_strip_path(func_name):
  418. filename, line, name = func_name
  419. return os.path.basename(filename), line, name
  420. def func_get_function_name(func):
  421. return func[2]
  422. def func_std_string(func_name): # match what old profile produced
  423. if func_name[:2] == ('~', 0):
  424. # special case for built-in functions
  425. name = func_name[2]
  426. if name.startswith('<') and name.endswith('>'):
  427. return '{%s}' % name[1:-1]
  428. else:
  429. return name
  430. else:
  431. return "%s:%d(%s)" % func_name
  432. #**************************************************************************
  433. # The following functions combine statists for pairs functions.
  434. # The bulk of the processing involves correctly handling "call" lists,
  435. # such as callers and callees.
  436. #**************************************************************************
  437. def add_func_stats(target, source):
  438. """Add together all the stats for two profile entries."""
  439. cc, nc, tt, ct, callers = source
  440. t_cc, t_nc, t_tt, t_ct, t_callers = target
  441. return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct,
  442. add_callers(t_callers, callers))
  443. def add_callers(target, source):
  444. """Combine two caller lists in a single list."""
  445. new_callers = {}
  446. for func, caller in target.iteritems():
  447. new_callers[func] = caller
  448. for func, caller in source.iteritems():
  449. if func in new_callers:
  450. if isinstance(caller, tuple):
  451. # format used by cProfile
  452. new_callers[func] = tuple([i[0] + i[1] for i in
  453. zip(caller, new_callers[func])])
  454. else:
  455. # format used by profile
  456. new_callers[func] += caller
  457. else:
  458. new_callers[func] = caller
  459. return new_callers
  460. def count_calls(callers):
  461. """Sum the caller statistics to get total number of calls received."""
  462. nc = 0
  463. for calls in callers.itervalues():
  464. nc += calls
  465. return nc
  466. #**************************************************************************
  467. # The following functions support printing of reports
  468. #**************************************************************************
  469. def f8(x):
  470. return "%8.3f" % x
  471. #**************************************************************************
  472. # Statistics browser added by ESR, April 2001
  473. #**************************************************************************
  474. if __name__ == '__main__':
  475. import cmd
  476. try:
  477. import readline
  478. except ImportError:
  479. pass
  480. class ProfileBrowser(cmd.Cmd):
  481. def __init__(self, profile=None):
  482. cmd.Cmd.__init__(self)
  483. self.prompt = "% "
  484. self.stats = None
  485. self.stream = sys.stdout
  486. if profile is not None:
  487. self.do_read(profile)
  488. def generic(self, fn, line):
  489. args = line.split()
  490. processed = []
  491. for term in args:
  492. try:
  493. processed.append(int(term))
  494. continue
  495. except ValueError:
  496. pass
  497. try:
  498. frac = float(term)
  499. if frac > 1 or frac < 0:
  500. print >> self.stream, "Fraction argument must be in [0, 1]"
  501. continue
  502. processed.append(frac)
  503. continue
  504. except ValueError:
  505. pass
  506. processed.append(term)
  507. if self.stats:
  508. getattr(self.stats, fn)(*processed)
  509. else:
  510. print >> self.stream, "No statistics object is loaded."
  511. return 0
  512. def generic_help(self):
  513. print >> self.stream, "Arguments may be:"
  514. print >> self.stream, "* An integer maximum number of entries to print."
  515. print >> self.stream, "* A decimal fractional number between 0 and 1, controlling"
  516. print >> self.stream, " what fraction of selected entries to print."
  517. print >> self.stream, "* A regular expression; only entries with function names"
  518. print >> self.stream, " that match it are printed."
  519. def do_add(self, line):
  520. if self.stats:
  521. self.stats.add(line)
  522. else:
  523. print >> self.stream, "No statistics object is loaded."
  524. return 0
  525. def help_add(self):
  526. print >> self.stream, "Add profile info from given file to current statistics object."
  527. def do_callees(self, line):
  528. return self.generic('print_callees', line)
  529. def help_callees(self):
  530. print >> self.stream, "Print callees statistics from the current stat object."
  531. self.generic_help()
  532. def do_callers(self, line):
  533. return self.generic('print_callers', line)
  534. def help_callers(self):
  535. print >> self.stream, "Print callers statistics from the current stat object."
  536. self.generic_help()
  537. def do_EOF(self, line):
  538. print >> self.stream, ""
  539. return 1
  540. def help_EOF(self):
  541. print >> self.stream, "Leave the profile brower."
  542. def do_quit(self, line):
  543. return 1
  544. def help_quit(self):
  545. print >> self.stream, "Leave the profile brower."
  546. def do_read(self, line):
  547. if line:
  548. try:
  549. self.stats = Stats(line)
  550. except IOError, args:
  551. print >> self.stream, args[1]
  552. return
  553. except Exception as err:
  554. print >> self.stream, err.__class__.__name__ + ':', err
  555. return
  556. self.prompt = line + "% "
  557. elif len(self.prompt) > 2:
  558. line = self.prompt[:-2]
  559. self.do_read(line)
  560. else:
  561. print >> self.stream, "No statistics object is current -- cannot reload."
  562. return 0
  563. def help_read(self):
  564. print >> self.stream, "Read in profile data from a specified file."
  565. print >> self.stream, "Without argument, reload the current file."
  566. def do_reverse(self, line):
  567. if self.stats:
  568. self.stats.reverse_order()
  569. else:
  570. print >> self.stream, "No statistics object is loaded."
  571. return 0
  572. def help_reverse(self):
  573. print >> self.stream, "Reverse the sort order of the profiling report."
  574. def do_sort(self, line):
  575. if not self.stats:
  576. print >> self.stream, "No statistics object is loaded."
  577. return
  578. abbrevs = self.stats.get_sort_arg_defs()
  579. if line and all((x in abbrevs) for x in line.split()):
  580. self.stats.sort_stats(*line.split())
  581. else:
  582. print >> self.stream, "Valid sort keys (unique prefixes are accepted):"
  583. for (key, value) in Stats.sort_arg_dict_default.iteritems():
  584. print >> self.stream, "%s -- %s" % (key, value[1])
  585. return 0
  586. def help_sort(self):
  587. print >> self.stream, "Sort profile data according to specified keys."
  588. print >> self.stream, "(Typing `sort' without arguments lists valid keys.)"
  589. def complete_sort(self, text, *args):
  590. return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
  591. def do_stats(self, line):
  592. return self.generic('print_stats', line)
  593. def help_stats(self):
  594. print >> self.stream, "Print statistics from the current stat object."
  595. self.generic_help()
  596. def do_strip(self, line):
  597. if self.stats:
  598. self.stats.strip_dirs()
  599. else:
  600. print >> self.stream, "No statistics object is loaded."
  601. def help_strip(self):
  602. print >> self.stream, "Strip leading path information from filenames in the report."
  603. def help_help(self):
  604. print >> self.stream, "Show help for a given command."
  605. def postcmd(self, stop, line):
  606. if stop:
  607. return stop
  608. return None
  609. import sys
  610. if len(sys.argv) > 1:
  611. initprofile = sys.argv[1]
  612. else:
  613. initprofile = None
  614. try:
  615. browser = ProfileBrowser(initprofile)
  616. print >> browser.stream, "Welcome to the profile statistics browser."
  617. browser.cmdloop()
  618. print >> browser.stream, "Goodbye."
  619. except KeyboardInterrupt:
  620. pass
  621. # That's all, folks.