pstats.py 27 KB

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