pstats.py 27 KB

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