pstats.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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 not fragment:
  199. break
  200. if fragment in dict:
  201. bad_list[fragment] = 0
  202. break
  203. dict[fragment] = tup
  204. fragment = fragment[:-1]
  205. for word in bad_list:
  206. del dict[word]
  207. return self.sort_arg_dict
  208. def sort_stats(self, *field):
  209. if not field:
  210. self.fcn_list = 0
  211. return self
  212. if len(field) == 1 and isinstance(field[0], int):
  213. # Be compatible with old profiler
  214. field = [ {-1: "stdname",
  215. 0: "calls",
  216. 1: "time",
  217. 2: "cumulative"}[field[0]] ]
  218. elif len(field) >= 2:
  219. for arg in field[1:]:
  220. if type(arg) != type(field[0]):
  221. raise TypeError("Can't have mixed argument type")
  222. sort_arg_defs = self.get_sort_arg_defs()
  223. sort_tuple = ()
  224. self.sort_type = ""
  225. connector = ""
  226. for word in field:
  227. if isinstance(word, SortKey):
  228. word = word.value
  229. sort_tuple = sort_tuple + sort_arg_defs[word][0]
  230. self.sort_type += connector + sort_arg_defs[word][1]
  231. connector = ", "
  232. stats_list = []
  233. for func, (cc, nc, tt, ct, callers) in self.stats.items():
  234. stats_list.append((cc, nc, tt, ct) + func +
  235. (func_std_string(func), func))
  236. stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))
  237. self.fcn_list = fcn_list = []
  238. for tuple in stats_list:
  239. fcn_list.append(tuple[-1])
  240. return self
  241. def reverse_order(self):
  242. if self.fcn_list:
  243. self.fcn_list.reverse()
  244. return self
  245. def strip_dirs(self):
  246. oldstats = self.stats
  247. self.stats = newstats = {}
  248. max_name_len = 0
  249. for func, (cc, nc, tt, ct, callers) in oldstats.items():
  250. newfunc = func_strip_path(func)
  251. if len(func_std_string(newfunc)) > max_name_len:
  252. max_name_len = len(func_std_string(newfunc))
  253. newcallers = {}
  254. for func2, caller in callers.items():
  255. newcallers[func_strip_path(func2)] = caller
  256. if newfunc in newstats:
  257. newstats[newfunc] = add_func_stats(
  258. newstats[newfunc],
  259. (cc, nc, tt, ct, newcallers))
  260. else:
  261. newstats[newfunc] = (cc, nc, tt, ct, newcallers)
  262. old_top = self.top_level
  263. self.top_level = new_top = set()
  264. for func in old_top:
  265. new_top.add(func_strip_path(func))
  266. self.max_name_len = max_name_len
  267. self.fcn_list = None
  268. self.all_callees = None
  269. return self
  270. def calc_callees(self):
  271. if self.all_callees:
  272. return
  273. self.all_callees = all_callees = {}
  274. for func, (cc, nc, tt, ct, callers) in self.stats.items():
  275. if not func in all_callees:
  276. all_callees[func] = {}
  277. for func2, caller in callers.items():
  278. if not func2 in all_callees:
  279. all_callees[func2] = {}
  280. all_callees[func2][func] = caller
  281. return
  282. #******************************************************************
  283. # The following functions support actual printing of reports
  284. #******************************************************************
  285. # Optional "amount" is either a line count, or a percentage of lines.
  286. def eval_print_amount(self, sel, list, msg):
  287. new_list = list
  288. if isinstance(sel, str):
  289. try:
  290. rex = re.compile(sel)
  291. except re.error:
  292. msg += " <Invalid regular expression %r>\n" % sel
  293. return new_list, msg
  294. new_list = []
  295. for func in list:
  296. if rex.search(func_std_string(func)):
  297. new_list.append(func)
  298. else:
  299. count = len(list)
  300. if isinstance(sel, float) and 0.0 <= sel < 1.0:
  301. count = int(count * sel + .5)
  302. new_list = list[:count]
  303. elif isinstance(sel, int) and 0 <= sel < count:
  304. count = sel
  305. new_list = list[:count]
  306. if len(list) != len(new_list):
  307. msg += " List reduced from %r to %r due to restriction <%r>\n" % (
  308. len(list), len(new_list), sel)
  309. return new_list, msg
  310. def get_stats_profile(self):
  311. """This method returns an instance of StatsProfile, which contains a mapping
  312. of function names to instances of FunctionProfile. Each FunctionProfile
  313. instance holds information related to the function's profile such as how
  314. long the function took to run, how many times it was called, etc...
  315. """
  316. func_list = self.fcn_list[:] if self.fcn_list else list(self.stats.keys())
  317. if not func_list:
  318. return StatsProfile(0, {})
  319. total_tt = float(f8(self.total_tt))
  320. func_profiles = {}
  321. stats_profile = StatsProfile(total_tt, func_profiles)
  322. for func in func_list:
  323. cc, nc, tt, ct, callers = self.stats[func]
  324. file_name, line_number, func_name = func
  325. ncalls = str(nc) if nc == cc else (str(nc) + '/' + str(cc))
  326. tottime = float(f8(tt))
  327. percall_tottime = -1 if nc == 0 else float(f8(tt/nc))
  328. cumtime = float(f8(ct))
  329. percall_cumtime = -1 if cc == 0 else float(f8(ct/cc))
  330. func_profile = FunctionProfile(
  331. ncalls,
  332. tottime, # time spent in this function alone
  333. percall_tottime,
  334. cumtime, # time spent in the function plus all functions that this function called,
  335. percall_cumtime,
  336. file_name,
  337. line_number
  338. )
  339. func_profiles[func_name] = func_profile
  340. return stats_profile
  341. def get_print_list(self, sel_list):
  342. width = self.max_name_len
  343. if self.fcn_list:
  344. stat_list = self.fcn_list[:]
  345. msg = " Ordered by: " + self.sort_type + '\n'
  346. else:
  347. stat_list = list(self.stats.keys())
  348. msg = " Random listing order was used\n"
  349. for selection in sel_list:
  350. stat_list, msg = self.eval_print_amount(selection, stat_list, msg)
  351. count = len(stat_list)
  352. if not stat_list:
  353. return 0, stat_list
  354. print(msg, file=self.stream)
  355. if count < len(self.stats):
  356. width = 0
  357. for func in stat_list:
  358. if len(func_std_string(func)) > width:
  359. width = len(func_std_string(func))
  360. return width+2, stat_list
  361. def print_stats(self, *amount):
  362. for filename in self.files:
  363. print(filename, file=self.stream)
  364. if self.files:
  365. print(file=self.stream)
  366. indent = ' ' * 8
  367. for func in self.top_level:
  368. print(indent, func_get_function_name(func), file=self.stream)
  369. print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
  370. if self.total_calls != self.prim_calls:
  371. print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
  372. print("in %.3f seconds" % self.total_tt, file=self.stream)
  373. print(file=self.stream)
  374. width, list = self.get_print_list(amount)
  375. if list:
  376. self.print_title()
  377. for func in list:
  378. self.print_line(func)
  379. print(file=self.stream)
  380. print(file=self.stream)
  381. return self
  382. def print_callees(self, *amount):
  383. width, list = self.get_print_list(amount)
  384. if list:
  385. self.calc_callees()
  386. self.print_call_heading(width, "called...")
  387. for func in list:
  388. if func in self.all_callees:
  389. self.print_call_line(width, func, self.all_callees[func])
  390. else:
  391. self.print_call_line(width, func, {})
  392. print(file=self.stream)
  393. print(file=self.stream)
  394. return self
  395. def print_callers(self, *amount):
  396. width, list = self.get_print_list(amount)
  397. if list:
  398. self.print_call_heading(width, "was called by...")
  399. for func in list:
  400. cc, nc, tt, ct, callers = self.stats[func]
  401. self.print_call_line(width, func, callers, "<-")
  402. print(file=self.stream)
  403. print(file=self.stream)
  404. return self
  405. def print_call_heading(self, name_size, column_title):
  406. print("Function ".ljust(name_size) + column_title, file=self.stream)
  407. # print sub-header only if we have new-style callers
  408. subheader = False
  409. for cc, nc, tt, ct, callers in self.stats.values():
  410. if callers:
  411. value = next(iter(callers.values()))
  412. subheader = isinstance(value, tuple)
  413. break
  414. if subheader:
  415. print(" "*name_size + " ncalls tottime cumtime", file=self.stream)
  416. def print_call_line(self, name_size, source, call_dict, arrow="->"):
  417. print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream)
  418. if not call_dict:
  419. print(file=self.stream)
  420. return
  421. clist = sorted(call_dict.keys())
  422. indent = ""
  423. for func in clist:
  424. name = func_std_string(func)
  425. value = call_dict[func]
  426. if isinstance(value, tuple):
  427. nc, cc, tt, ct = value
  428. if nc != cc:
  429. substats = '%d/%d' % (nc, cc)
  430. else:
  431. substats = '%d' % (nc,)
  432. substats = '%s %s %s %s' % (substats.rjust(7+2*len(indent)),
  433. f8(tt), f8(ct), name)
  434. left_width = name_size + 1
  435. else:
  436. substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
  437. left_width = name_size + 3
  438. print(indent*left_width + substats, file=self.stream)
  439. indent = " "
  440. def print_title(self):
  441. print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream)
  442. print('filename:lineno(function)', file=self.stream)
  443. def print_line(self, func): # hack: should print percentages
  444. cc, nc, tt, ct, callers = self.stats[func]
  445. c = str(nc)
  446. if nc != cc:
  447. c = c + '/' + str(cc)
  448. print(c.rjust(9), end=' ', file=self.stream)
  449. print(f8(tt), end=' ', file=self.stream)
  450. if nc == 0:
  451. print(' '*8, end=' ', file=self.stream)
  452. else:
  453. print(f8(tt/nc), end=' ', file=self.stream)
  454. print(f8(ct), end=' ', file=self.stream)
  455. if cc == 0:
  456. print(' '*8, end=' ', file=self.stream)
  457. else:
  458. print(f8(ct/cc), end=' ', file=self.stream)
  459. print(func_std_string(func), file=self.stream)
  460. class TupleComp:
  461. """This class provides a generic function for comparing any two tuples.
  462. Each instance records a list of tuple-indices (from most significant
  463. to least significant), and sort direction (ascending or descending) for
  464. each tuple-index. The compare functions can then be used as the function
  465. argument to the system sort() function when a list of tuples need to be
  466. sorted in the instances order."""
  467. def __init__(self, comp_select_list):
  468. self.comp_select_list = comp_select_list
  469. def compare (self, left, right):
  470. for index, direction in self.comp_select_list:
  471. l = left[index]
  472. r = right[index]
  473. if l < r:
  474. return -direction
  475. if l > r:
  476. return direction
  477. return 0
  478. #**************************************************************************
  479. # func_name is a triple (file:string, line:int, name:string)
  480. def func_strip_path(func_name):
  481. filename, line, name = func_name
  482. return os.path.basename(filename), line, name
  483. def func_get_function_name(func):
  484. return func[2]
  485. def func_std_string(func_name): # match what old profile produced
  486. if func_name[:2] == ('~', 0):
  487. # special case for built-in functions
  488. name = func_name[2]
  489. if name.startswith('<') and name.endswith('>'):
  490. return '{%s}' % name[1:-1]
  491. else:
  492. return name
  493. else:
  494. return "%s:%d(%s)" % func_name
  495. #**************************************************************************
  496. # The following functions combine statistics for pairs functions.
  497. # The bulk of the processing involves correctly handling "call" lists,
  498. # such as callers and callees.
  499. #**************************************************************************
  500. def add_func_stats(target, source):
  501. """Add together all the stats for two profile entries."""
  502. cc, nc, tt, ct, callers = source
  503. t_cc, t_nc, t_tt, t_ct, t_callers = target
  504. return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct,
  505. add_callers(t_callers, callers))
  506. def add_callers(target, source):
  507. """Combine two caller lists in a single list."""
  508. new_callers = {}
  509. for func, caller in target.items():
  510. new_callers[func] = caller
  511. for func, caller in source.items():
  512. if func in new_callers:
  513. if isinstance(caller, tuple):
  514. # format used by cProfile
  515. new_callers[func] = tuple(i + j for i, j in zip(caller, new_callers[func]))
  516. else:
  517. # format used by profile
  518. new_callers[func] += caller
  519. else:
  520. new_callers[func] = caller
  521. return new_callers
  522. def count_calls(callers):
  523. """Sum the caller statistics to get total number of calls received."""
  524. nc = 0
  525. for calls in callers.values():
  526. nc += calls
  527. return nc
  528. #**************************************************************************
  529. # The following functions support printing of reports
  530. #**************************************************************************
  531. def f8(x):
  532. return "%8.3f" % x
  533. #**************************************************************************
  534. # Statistics browser added by ESR, April 2001
  535. #**************************************************************************
  536. if __name__ == '__main__':
  537. import cmd
  538. try:
  539. import readline
  540. except ImportError:
  541. pass
  542. class ProfileBrowser(cmd.Cmd):
  543. def __init__(self, profile=None):
  544. cmd.Cmd.__init__(self)
  545. self.prompt = "% "
  546. self.stats = None
  547. self.stream = sys.stdout
  548. if profile is not None:
  549. self.do_read(profile)
  550. def generic(self, fn, line):
  551. args = line.split()
  552. processed = []
  553. for term in args:
  554. try:
  555. processed.append(int(term))
  556. continue
  557. except ValueError:
  558. pass
  559. try:
  560. frac = float(term)
  561. if frac > 1 or frac < 0:
  562. print("Fraction argument must be in [0, 1]", file=self.stream)
  563. continue
  564. processed.append(frac)
  565. continue
  566. except ValueError:
  567. pass
  568. processed.append(term)
  569. if self.stats:
  570. getattr(self.stats, fn)(*processed)
  571. else:
  572. print("No statistics object is loaded.", file=self.stream)
  573. return 0
  574. def generic_help(self):
  575. print("Arguments may be:", file=self.stream)
  576. print("* An integer maximum number of entries to print.", file=self.stream)
  577. print("* A decimal fractional number between 0 and 1, controlling", file=self.stream)
  578. print(" what fraction of selected entries to print.", file=self.stream)
  579. print("* A regular expression; only entries with function names", file=self.stream)
  580. print(" that match it are printed.", file=self.stream)
  581. def do_add(self, line):
  582. if self.stats:
  583. try:
  584. self.stats.add(line)
  585. except OSError as e:
  586. print("Failed to load statistics for %s: %s" % (line, e), file=self.stream)
  587. else:
  588. print("No statistics object is loaded.", file=self.stream)
  589. return 0
  590. def help_add(self):
  591. print("Add profile info from given file to current statistics object.", file=self.stream)
  592. def do_callees(self, line):
  593. return self.generic('print_callees', line)
  594. def help_callees(self):
  595. print("Print callees statistics from the current stat object.", file=self.stream)
  596. self.generic_help()
  597. def do_callers(self, line):
  598. return self.generic('print_callers', line)
  599. def help_callers(self):
  600. print("Print callers statistics from the current stat object.", file=self.stream)
  601. self.generic_help()
  602. def do_EOF(self, line):
  603. print("", file=self.stream)
  604. return 1
  605. def help_EOF(self):
  606. print("Leave the profile browser.", file=self.stream)
  607. def do_quit(self, line):
  608. return 1
  609. def help_quit(self):
  610. print("Leave the profile browser.", file=self.stream)
  611. def do_read(self, line):
  612. if line:
  613. try:
  614. self.stats = Stats(line)
  615. except OSError as err:
  616. print(err.args[1], file=self.stream)
  617. return
  618. except Exception as err:
  619. print(err.__class__.__name__ + ':', err, file=self.stream)
  620. return
  621. self.prompt = line + "% "
  622. elif len(self.prompt) > 2:
  623. line = self.prompt[:-2]
  624. self.do_read(line)
  625. else:
  626. print("No statistics object is current -- cannot reload.", file=self.stream)
  627. return 0
  628. def help_read(self):
  629. print("Read in profile data from a specified file.", file=self.stream)
  630. print("Without argument, reload the current file.", file=self.stream)
  631. def do_reverse(self, line):
  632. if self.stats:
  633. self.stats.reverse_order()
  634. else:
  635. print("No statistics object is loaded.", file=self.stream)
  636. return 0
  637. def help_reverse(self):
  638. print("Reverse the sort order of the profiling report.", file=self.stream)
  639. def do_sort(self, line):
  640. if not self.stats:
  641. print("No statistics object is loaded.", file=self.stream)
  642. return
  643. abbrevs = self.stats.get_sort_arg_defs()
  644. if line and all((x in abbrevs) for x in line.split()):
  645. self.stats.sort_stats(*line.split())
  646. else:
  647. print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
  648. for (key, value) in Stats.sort_arg_dict_default.items():
  649. print("%s -- %s" % (key, value[1]), file=self.stream)
  650. return 0
  651. def help_sort(self):
  652. print("Sort profile data according to specified keys.", file=self.stream)
  653. print("(Typing `sort' without arguments lists valid keys.)", file=self.stream)
  654. def complete_sort(self, text, *args):
  655. return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
  656. def do_stats(self, line):
  657. return self.generic('print_stats', line)
  658. def help_stats(self):
  659. print("Print statistics from the current stat object.", file=self.stream)
  660. self.generic_help()
  661. def do_strip(self, line):
  662. if self.stats:
  663. self.stats.strip_dirs()
  664. else:
  665. print("No statistics object is loaded.", file=self.stream)
  666. def help_strip(self):
  667. print("Strip leading path information from filenames in the report.", file=self.stream)
  668. def help_help(self):
  669. print("Show help for a given command.", file=self.stream)
  670. def postcmd(self, stop, line):
  671. if stop:
  672. return stop
  673. return None
  674. if len(sys.argv) > 1:
  675. initprofile = sys.argv[1]
  676. else:
  677. initprofile = None
  678. try:
  679. browser = ProfileBrowser(initprofile)
  680. for profile in sys.argv[2:]:
  681. browser.do_add(profile)
  682. print("Welcome to the profile statistics browser.", file=browser.stream)
  683. browser.cmdloop()
  684. print("Goodbye.", file=browser.stream)
  685. except KeyboardInterrupt:
  686. pass
  687. # That's all, folks.