home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / pstats.py < prev    next >
Text File  |  2000-12-21  |  16KB  |  527 lines

  1. """Class for printing reports on profiled python code."""
  2.  
  3. # Class for printing reports on profiled python code. rev 1.0  4/1/94
  4. #
  5. # Based on prior profile module by Sjoerd Mullender...
  6. #   which was hacked somewhat by: Guido van Rossum
  7. #
  8. # see profile.doc and profile.py for more info.
  9.  
  10. # Copyright 1994, by InfoSeek Corporation, all rights reserved.
  11. # Written by James Roskind
  12. # Permission to use, copy, modify, and distribute this Python software
  13. # and its associated documentation for any purpose (subject to the
  14. # restriction in the following sentence) without fee is hereby granted,
  15. # provided that the above copyright notice appears in all copies, and
  16. # that both that copyright notice and this permission notice appear in
  17. # supporting documentation, and that the name of InfoSeek not be used in
  18. # advertising or publicity pertaining to distribution of the software
  19. # without specific, written prior permission.  This permission is
  20. # explicitly restricted to the copying and modification of the software
  21. # to remain in Python, compiled Python, or other languages (such as C)
  22. # wherein the modified or derived code is exclusively imported into a
  23. # Python module.
  24. # INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
  25. # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  26. # FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
  27. # SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
  28. # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  29. # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  30. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  31.  
  32.  
  33. import os
  34. import time
  35. import string
  36. import marshal
  37. import re
  38.  
  39. import fpformat
  40.  
  41. class Stats:
  42.     """This class is used for creating reports from data generated by the
  43.     Profile class.  It is a "friend" of that class, and imports data either
  44.     by direct access to members of Profile class, or by reading in a dictionary
  45.     that was emitted (via marshal) from the Profile class.
  46.  
  47.     The big change from the previous Profiler (in terms of raw functionality)
  48.     is that an "add()" method has been provided to combine Stats from
  49.     several distinct profile runs.  Both the constructor and the add()
  50.     method now take arbitrarilly many file names as arguments.
  51.  
  52.     All the print methods now take an argument that indicats how many lines
  53.     to print.  If the arg is a floating point number between 0 and 1.0, then
  54.     it is taken as a decimal percentage of the availabel lines to be printed
  55.     (e.g., .1 means print 10% of all available lines).  If it is an integer,
  56.     it is taken to mean the number of lines of data that you wish to have
  57.     printed.
  58.  
  59.     The sort_stats() method now processes some additionaly options (i.e., in
  60.     addition to the old -1, 0, 1, or 2).  It takes an arbitrary number of quoted
  61.     strings to select the sort order.  For example sort_stats('time', 'name')
  62.     sorts on the major key of "internal function time", and on the minor
  63.     key of 'the name of the function'.  Look at the two tables in sort_stats()
  64.     and get_sort_arg_defs(self) for more examples.
  65.  
  66.     All methods now return "self",  so you can string together commands like:
  67.         Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
  68.                             print_stats(5).print_callers(5)
  69.     """
  70.     
  71.     def __init__(self, *args):
  72.         if not len(args):
  73.             arg = None
  74.         else:
  75.             arg = args[0]
  76.             args = args[1:]
  77.         self.init(arg)
  78.         apply(self.add, args).ignore()
  79.             
  80.     def init(self, arg):
  81.         self.all_callees = None  # calc only if needed
  82.         self.files = []
  83.         self.fcn_list = None
  84.         self.total_tt = 0
  85.         self.total_calls = 0
  86.         self.prim_calls = 0
  87.         self.max_name_len = 0
  88.         self.top_level = {}
  89.         self.stats = {}
  90.         self.sort_arg_dict = {}
  91.         self.load_stats(arg)
  92.         trouble = 1
  93.         try:
  94.             self.get_top_level_stats()
  95.             trouble = 0
  96.         finally:
  97.             if trouble:
  98.                 print "Invalid timing data",
  99.                 if self.files: print self.files[-1],
  100.                 print
  101.  
  102.  
  103.     def load_stats(self, arg):
  104.         if not arg:  self.stats = {}
  105.         elif type(arg) == type(""):
  106.             f = open(arg, 'rb')
  107.             self.stats = marshal.load(f)
  108.             f.close()
  109.             try:
  110.                 file_stats = os.stat(arg)
  111.                 arg = time.ctime(file_stats[8]) + "    " + arg
  112.             except:  # in case this is not unix
  113.                 pass
  114.             self.files = [ arg ]
  115.         elif hasattr(arg, 'create_stats'):
  116.             arg.create_stats()
  117.             self.stats = arg.stats
  118.             arg.stats = {}
  119.         if not self.stats:
  120.             raise TypeError,  "Cannot create or construct a " \
  121.                   + `self.__class__` \
  122.                   + " object from '" + `arg` + "'"
  123.         return
  124.  
  125.     def get_top_level_stats(self):
  126.         for func in self.stats.keys():
  127.             cc, nc, tt, ct, callers = self.stats[func]
  128.             self.total_calls = self.total_calls + nc
  129.             self.prim_calls  = self.prim_calls  + cc
  130.             self.total_tt    = self.total_tt    + tt
  131.             if callers.has_key(("jprofile", 0, "profiler")):
  132.                 self.top_level[func] = None
  133.             if len(func_std_string(func)) > self.max_name_len:
  134.                 self.max_name_len = len(func_std_string(func))
  135.                     
  136.     def add(self, *arg_list):
  137.         if not arg_list: return self
  138.         if len(arg_list) > 1: apply(self.add, arg_list[1:])
  139.         other = arg_list[0]
  140.         if type(self) != type(other) or \
  141.               self.__class__ != other.__class__:
  142.             other = Stats(other)
  143.         self.files = self.files + other.files
  144.         self.total_calls = self.total_calls + other.total_calls
  145.         self.prim_calls = self.prim_calls + other.prim_calls
  146.         self.total_tt = self.total_tt + other.total_tt
  147.         for func in other.top_level.keys():
  148.             self.top_level[func] = None
  149.  
  150.         if self.max_name_len < other.max_name_len:
  151.             self.max_name_len = other.max_name_len
  152.  
  153.         self.fcn_list = None
  154.  
  155.         for func in other.stats.keys():
  156.             if self.stats.has_key(func):
  157.                 old_func_stat = self.stats[func]
  158.             else:
  159.                 old_func_stat = (0, 0, 0, 0, {},)
  160.             self.stats[func] = add_func_stats(old_func_stat, \
  161.                   other.stats[func])
  162.         return self
  163.             
  164.  
  165.  
  166.     # list the tuple indicies and directions for sorting,
  167.     # along with some printable description
  168.     sort_arg_dict_default = {\
  169.           "calls"     : (((1,-1),              ), "call count"),\
  170.           "cumulative": (((3,-1),              ), "cumulative time"),\
  171.           "file"      : (((4, 1),              ), "file name"),\
  172.           "line"      : (((5, 1),              ), "line number"),\
  173.           "module"    : (((4, 1),              ), "file name"),\
  174.           "name"      : (((6, 1),              ), "function name"),\
  175.           "nfl"       : (((6, 1),(4, 1),(5, 1),), "name/file/line"), \
  176.           "pcalls"    : (((0,-1),              ), "call count"),\
  177.           "stdname"   : (((7, 1),              ), "standard name"),\
  178.           "time"      : (((2,-1),              ), "internal time"),\
  179.           }
  180.  
  181.     def get_sort_arg_defs(self):
  182.         """Expand all abbreviations that are unique."""
  183.         if not self.sort_arg_dict:
  184.             self.sort_arg_dict = dict = {}
  185.             std_list = dict.keys()
  186.             bad_list = {}
  187.             for word in self.sort_arg_dict_default.keys():
  188.                 fragment = word
  189.                 while fragment:
  190.                     if not fragment:
  191.                         break
  192.                     if dict.has_key(fragment):
  193.                         bad_list[fragment] = 0
  194.                         break
  195.                     dict[fragment] = self. \
  196.                           sort_arg_dict_default[word]
  197.                     fragment = fragment[:-1]
  198.             for word in bad_list.keys():
  199.                 del dict[word]
  200.         return self.sort_arg_dict
  201.             
  202.  
  203.     def sort_stats(self, *field):
  204.         if not field:
  205.             self.fcn_list = 0
  206.             return self
  207.         if len(field) == 1 and type(field[0]) == type(1):
  208.             # Be compatible with old profiler
  209.             field = [ {-1: "stdname", \
  210.                   0:"calls", \
  211.                   1:"time", \
  212.                   2: "cumulative" }  [ field[0] ] ]
  213.  
  214.         sort_arg_defs = self.get_sort_arg_defs()
  215.         sort_tuple = ()
  216.         self.sort_type = ""
  217.         connector = ""
  218.         for word in field:
  219.             sort_tuple = sort_tuple + sort_arg_defs[word][0]
  220.             self.sort_type = self.sort_type + connector + \
  221.                   sort_arg_defs[word][1]
  222.             connector = ", "
  223.                     
  224.         stats_list = []
  225.         for func in self.stats.keys():
  226.             cc, nc, tt, ct, callers = self.stats[func]
  227.             stats_list.append((cc, nc, tt, ct) + func_split(func) \
  228.                            + (func_std_string(func), func,)  )
  229.  
  230.         stats_list.sort(TupleComp(sort_tuple).compare)
  231.  
  232.         self.fcn_list = fcn_list = []
  233.         for tuple in stats_list:
  234.             fcn_list.append(tuple[-1])
  235.         return self
  236.  
  237.  
  238.     def reverse_order(self):
  239.         if self.fcn_list: self.fcn_list.reverse()
  240.         return self
  241.  
  242.     def strip_dirs(self):
  243.         oldstats = self.stats
  244.         self.stats = newstats = {}
  245.         max_name_len = 0
  246.         for func in oldstats.keys():
  247.             cc, nc, tt, ct, callers = oldstats[func]
  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 in callers.keys():
  253.                 newcallers[func_strip_path(func2)] = \
  254.                       callers[func2]
  255.  
  256.             if newstats.has_key(newfunc):
  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 = {}
  264.         for func in old_top.keys():
  265.             new_top[func_strip_path(func)] = None
  266.  
  267.         self.max_name_len = max_name_len
  268.  
  269.         self.fcn_list = None
  270.         self.all_callees = None
  271.         return self
  272.  
  273.  
  274.  
  275.     def calc_callees(self):
  276.         if self.all_callees: return
  277.         self.all_callees = all_callees = {}
  278.         for func in self.stats.keys():
  279.             if not all_callees.has_key(func):
  280.                 all_callees[func] = {}
  281.             cc, nc, tt, ct, callers = self.stats[func]
  282.             for func2 in callers.keys():
  283.                 if not all_callees.has_key(func2):
  284.                     all_callees[func2] = {}
  285.                 all_callees[func2][func]  = callers[func2]
  286.         return
  287.  
  288.     #******************************************************************
  289.     # The following functions support actual printing of reports
  290.     #******************************************************************
  291.  
  292.     # Optional "amount" is either a line count, or a percentage of lines.
  293.  
  294.     def eval_print_amount(self, sel, list, msg):
  295.         new_list = list
  296.         if type(sel) == type(""):
  297.             new_list = []
  298.             for func in list:
  299.                 if re.search(sel, func_std_string(func)):
  300.                     new_list.append(func)
  301.         else:
  302.             count = len(list)
  303.             if type(sel) == type(1.0) and 0.0 <= sel < 1.0:
  304.                 count = int (count * sel + .5)
  305.                 new_list = list[:count]
  306.             elif type(sel) == type(1) and 0 <= sel < count:
  307.                 count = sel
  308.                 new_list = list[:count]
  309.         if len(list) != len(new_list):
  310.             msg = msg + "   List reduced from " + `len(list)` \
  311.                   + " to " + `len(new_list)` + \
  312.                   " due to restriction <" + `sel` + ">\n"
  313.             
  314.         return new_list, msg
  315.  
  316.  
  317.  
  318.     def get_print_list(self, sel_list):
  319.         width = self.max_name_len
  320.         if self.fcn_list:
  321.             list = self.fcn_list[:]
  322.             msg = "   Ordered by: " + self.sort_type + '\n'
  323.         else:
  324.             list = self.stats.keys()
  325.             msg = "   Random listing order was used\n"
  326.  
  327.         for selection in sel_list:
  328.             list,msg = self.eval_print_amount(selection, list, msg)
  329.  
  330.         count = len(list)
  331.  
  332.         if not list:
  333.             return 0, list
  334.         print msg
  335.         if count < len(self.stats):
  336.             width = 0
  337.             for func in list:
  338.                 if  len(func_std_string(func)) > width:
  339.                     width = len(func_std_string(func))
  340.         return width+2, list
  341.         
  342.     def print_stats(self, *amount):
  343.         for filename in self.files:
  344.             print filename
  345.         if self.files: print
  346.         indent = "        "
  347.         for func in self.top_level.keys():
  348.             print indent, func_get_function_name(func)
  349.         
  350.         print  indent, self.total_calls, "function calls",
  351.         if self.total_calls != self.prim_calls:
  352.             print "(" + `self.prim_calls`, "primitive calls)", 
  353.         print "in", fpformat.fix(self.total_tt, 3), "CPU seconds"
  354.         print
  355.         width, list = self.get_print_list(amount)
  356.         if list:
  357.             self.print_title()
  358.             for func in list:
  359.                 self.print_line(func)
  360.             print 
  361.             print
  362.         return self
  363.  
  364.             
  365.     def print_callees(self, *amount):
  366.         width, list = self.get_print_list(amount)
  367.         if list:
  368.             self.calc_callees()
  369.  
  370.             self.print_call_heading(width, "called...")
  371.             for func in list:
  372.                 if self.all_callees.has_key(func):
  373.                     self.print_call_line(width, \
  374.                           func, self.all_callees[func])
  375.                 else:
  376.                     self.print_call_line(width, func, {})
  377.             print
  378.             print
  379.         return self
  380.  
  381.     def print_callers(self, *amount):
  382.         width, list = self.get_print_list(amount)
  383.         if list:
  384.             self.print_call_heading(width, "was called by...")
  385.             for func in list:
  386.                 cc, nc, tt, ct, callers = self.stats[func]
  387.                 self.print_call_line(width, func, callers)
  388.             print
  389.             print
  390.         return self
  391.  
  392.     def print_call_heading(self, name_size, column_title):
  393.         print string.ljust("Function ", name_size) + column_title
  394.  
  395.  
  396.     def print_call_line(self, name_size, source, call_dict):
  397.         print string.ljust(func_std_string(source), name_size),
  398.         if not call_dict:
  399.             print "--"
  400.             return
  401.         clist = call_dict.keys()
  402.         clist.sort()
  403.         name_size = name_size + 1
  404.         indent = ""
  405.         for func in clist:
  406.             name = func_std_string(func)
  407.             print indent*name_size + name + '(' \
  408.                   + `call_dict[func]`+')', \
  409.                   f8(self.stats[func][3])
  410.             indent = " "
  411.  
  412.  
  413.  
  414.     def print_title(self):
  415.         print string.rjust('ncalls', 9),
  416.         print string.rjust('tottime', 8),
  417.         print string.rjust('percall', 8),
  418.         print string.rjust('cumtime', 8),
  419.         print string.rjust('percall', 8),
  420.         print 'filename:lineno(function)'
  421.  
  422.  
  423.     def print_line(self, func):  # hack : should print percentages
  424.         cc, nc, tt, ct, callers = self.stats[func]
  425.         c = `nc`
  426.         if nc != cc:
  427.             c = c + '/' + `cc`
  428.         print string.rjust(c, 9),
  429.         print f8(tt),
  430.         if nc == 0:
  431.             print ' '*8,
  432.         else:
  433.             print f8(tt/nc),
  434.         print f8(ct),
  435.         if cc == 0:
  436.             print ' '*8,
  437.         else:
  438.             print f8(ct/cc),
  439.         print func_std_string(func)
  440.  
  441.  
  442.     def ignore(self):
  443.         pass # has no return value, so use at end of line :-)
  444.  
  445.  
  446. class TupleComp:
  447.     """This class provides a generic function for comparing any two tuples.
  448.     Each instance records a list of tuple-indicies (from most significant
  449.     to least significant), and sort direction (ascending or decending) for
  450.     each tuple-index.  The compare functions can then be used as the function
  451.     argument to the system sort() function when a list of tuples need to be
  452.     sorted in the instances order."""
  453.  
  454.     def __init__(self, comp_select_list):
  455.         self.comp_select_list = comp_select_list
  456.  
  457.     def compare (self, left, right):
  458.         for index, direction in self.comp_select_list:
  459.             l = left[index]
  460.             r = right[index]
  461.             if l < r:
  462.                 return -direction
  463.             if l > r:
  464.                 return direction
  465.         return 0
  466.  
  467.         
  468.  
  469. #**************************************************************************
  470.  
  471. def func_strip_path(func_name):
  472.     file, line, name = func_name
  473.     return os.path.basename(file), line, name
  474.  
  475. def func_get_function_name(func):
  476.     return func[2]
  477.  
  478. def func_std_string(func_name): # match what old profile produced
  479.     file, line, name = func_name
  480.     return file + ":" + `line` + "(" + name + ")"
  481.  
  482. def func_split(func_name):
  483.     return func_name
  484.  
  485. #**************************************************************************
  486. # The following functions combine statists for pairs functions.
  487. # The bulk of the processing involves correctly handling "call" lists,
  488. # such as callers and callees. 
  489. #**************************************************************************
  490.  
  491. def add_func_stats(target, source):
  492.     """Add together all the stats for two profile entries."""
  493.     cc, nc, tt, ct, callers = source
  494.     t_cc, t_nc, t_tt, t_ct, t_callers = target
  495.     return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct, \
  496.           add_callers(t_callers, callers))
  497.  
  498.  
  499. def add_callers(target, source):
  500.     """Combine two caller lists in a single list."""
  501.     new_callers = {}
  502.     for func in target.keys():
  503.         new_callers[func] = target[func]
  504.     for func in source.keys():
  505.         if new_callers.has_key(func):
  506.             new_callers[func] = source[func] + new_callers[func]
  507.         else:
  508.             new_callers[func] = source[func]
  509.     return new_callers
  510.  
  511. def count_calls(callers):
  512.     """Sum the caller statistics to get total number of calls received."""
  513.     nc = 0
  514.     for func in callers.keys():
  515.         nc = nc + callers[func]
  516.     return nc
  517.  
  518. #**************************************************************************
  519. # The following functions support printing of reports
  520. #**************************************************************************
  521.  
  522. def f8(x):
  523.     return string.rjust(fpformat.fix(x, 3), 8)
  524.  
  525.