pstats.py 29 KB

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