pstats.py 29 KB

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