Blame Lib/pstats.py

rpm-build 2bd099
"""Class for printing reports on profiled python code."""
rpm-build 2bd099
rpm-build 2bd099
# Written by James Roskind
rpm-build 2bd099
# Based on prior profile module by Sjoerd Mullender...
rpm-build 2bd099
#   which was hacked somewhat by: Guido van Rossum
rpm-build 2bd099
rpm-build 2bd099
# Copyright Disney Enterprises, Inc.  All Rights Reserved.
rpm-build 2bd099
# Licensed to PSF under a Contributor Agreement
rpm-build 2bd099
#
rpm-build 2bd099
# Licensed under the Apache License, Version 2.0 (the "License");
rpm-build 2bd099
# you may not use this file except in compliance with the License.
rpm-build 2bd099
# You may obtain a copy of the License at
rpm-build 2bd099
#
rpm-build 2bd099
# http://www.apache.org/licenses/LICENSE-2.0
rpm-build 2bd099
#
rpm-build 2bd099
# Unless required by applicable law or agreed to in writing, software
rpm-build 2bd099
# distributed under the License is distributed on an "AS IS" BASIS,
rpm-build 2bd099
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
rpm-build 2bd099
# either express or implied.  See the License for the specific language
rpm-build 2bd099
# governing permissions and limitations under the License.
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
import sys
rpm-build 2bd099
import os
rpm-build 2bd099
import time
rpm-build 2bd099
import marshal
rpm-build 2bd099
import re
rpm-build 2bd099
from functools import cmp_to_key
rpm-build 2bd099
rpm-build 2bd099
__all__ = ["Stats"]
rpm-build 2bd099
rpm-build 2bd099
class Stats:
rpm-build 2bd099
    """This class is used for creating reports from data generated by the
rpm-build 2bd099
    Profile class.  It is a "friend" of that class, and imports data either
rpm-build 2bd099
    by direct access to members of Profile class, or by reading in a dictionary
rpm-build 2bd099
    that was emitted (via marshal) from the Profile class.
rpm-build 2bd099
rpm-build 2bd099
    The big change from the previous Profiler (in terms of raw functionality)
rpm-build 2bd099
    is that an "add()" method has been provided to combine Stats from
rpm-build 2bd099
    several distinct profile runs.  Both the constructor and the add()
rpm-build 2bd099
    method now take arbitrarily many file names as arguments.
rpm-build 2bd099
rpm-build 2bd099
    All the print methods now take an argument that indicates how many lines
rpm-build 2bd099
    to print.  If the arg is a floating point number between 0 and 1.0, then
rpm-build 2bd099
    it is taken as a decimal percentage of the available lines to be printed
rpm-build 2bd099
    (e.g., .1 means print 10% of all available lines).  If it is an integer,
rpm-build 2bd099
    it is taken to mean the number of lines of data that you wish to have
rpm-build 2bd099
    printed.
rpm-build 2bd099
rpm-build 2bd099
    The sort_stats() method now processes some additional options (i.e., in
rpm-build 2bd099
    addition to the old -1, 0, 1, or 2 that are respectively interpreted as
rpm-build 2bd099
    'stdname', 'calls', 'time', and 'cumulative').  It takes an arbitrary number
rpm-build 2bd099
    of quoted strings to select the sort order.
rpm-build 2bd099
rpm-build 2bd099
    For example sort_stats('time', 'name') sorts on the major key of 'internal
rpm-build 2bd099
    function time', and on the minor key of 'the name of the function'.  Look at
rpm-build 2bd099
    the two tables in sort_stats() and get_sort_arg_defs(self) for more
rpm-build 2bd099
    examples.
rpm-build 2bd099
rpm-build 2bd099
    All methods return self, so you can string together commands like:
rpm-build 2bd099
        Stats('foo', 'goo').strip_dirs().sort_stats('calls').\
rpm-build 2bd099
                            print_stats(5).print_callers(5)
rpm-build 2bd099
    """
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, *args, stream=None):
rpm-build 2bd099
        self.stream = stream or sys.stdout
rpm-build 2bd099
        if not len(args):
rpm-build 2bd099
            arg = None
rpm-build 2bd099
        else:
rpm-build 2bd099
            arg = args[0]
rpm-build 2bd099
            args = args[1:]
rpm-build 2bd099
        self.init(arg)
rpm-build 2bd099
        self.add(*args)
rpm-build 2bd099
rpm-build 2bd099
    def init(self, arg):
rpm-build 2bd099
        self.all_callees = None  # calc only if needed
rpm-build 2bd099
        self.files = []
rpm-build 2bd099
        self.fcn_list = None
rpm-build 2bd099
        self.total_tt = 0
rpm-build 2bd099
        self.total_calls = 0
rpm-build 2bd099
        self.prim_calls = 0
rpm-build 2bd099
        self.max_name_len = 0
rpm-build 2bd099
        self.top_level = set()
rpm-build 2bd099
        self.stats = {}
rpm-build 2bd099
        self.sort_arg_dict = {}
rpm-build 2bd099
        self.load_stats(arg)
rpm-build 2bd099
        try:
rpm-build 2bd099
            self.get_top_level_stats()
rpm-build 2bd099
        except Exception:
rpm-build 2bd099
            print("Invalid timing data %s" %
rpm-build 2bd099
                  (self.files[-1] if self.files else ''), file=self.stream)
rpm-build 2bd099
            raise
rpm-build 2bd099
rpm-build 2bd099
    def load_stats(self, arg):
rpm-build 2bd099
        if arg is None:
rpm-build 2bd099
            self.stats = {}
rpm-build 2bd099
            return
rpm-build 2bd099
        elif isinstance(arg, str):
rpm-build 2bd099
            with open(arg, 'rb') as f:
rpm-build 2bd099
                self.stats = marshal.load(f)
rpm-build 2bd099
            try:
rpm-build 2bd099
                file_stats = os.stat(arg)
rpm-build 2bd099
                arg = time.ctime(file_stats.st_mtime) + "    " + arg
rpm-build 2bd099
            except:  # in case this is not unix
rpm-build 2bd099
                pass
rpm-build 2bd099
            self.files = [arg]
rpm-build 2bd099
        elif hasattr(arg, 'create_stats'):
rpm-build 2bd099
            arg.create_stats()
rpm-build 2bd099
            self.stats = arg.stats
rpm-build 2bd099
            arg.stats = {}
rpm-build 2bd099
        if not self.stats:
rpm-build 2bd099
            raise TypeError("Cannot create or construct a %r object from %r"
rpm-build 2bd099
                            % (self.__class__, arg))
rpm-build 2bd099
        return
rpm-build 2bd099
rpm-build 2bd099
    def get_top_level_stats(self):
rpm-build 2bd099
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
rpm-build 2bd099
            self.total_calls += nc
rpm-build 2bd099
            self.prim_calls  += cc
rpm-build 2bd099
            self.total_tt    += tt
rpm-build 2bd099
            if ("jprofile", 0, "profiler") in callers:
rpm-build 2bd099
                self.top_level.add(func)
rpm-build 2bd099
            if len(func_std_string(func)) > self.max_name_len:
rpm-build 2bd099
                self.max_name_len = len(func_std_string(func))
rpm-build 2bd099
rpm-build 2bd099
    def add(self, *arg_list):
rpm-build 2bd099
        if not arg_list:
rpm-build 2bd099
            return self
rpm-build 2bd099
        for item in reversed(arg_list):
rpm-build 2bd099
            if type(self) != type(item):
rpm-build 2bd099
                item = Stats(item)
rpm-build 2bd099
            self.files += item.files
rpm-build 2bd099
            self.total_calls += item.total_calls
rpm-build 2bd099
            self.prim_calls += item.prim_calls
rpm-build 2bd099
            self.total_tt += item.total_tt
rpm-build 2bd099
            for func in item.top_level:
rpm-build 2bd099
                self.top_level.add(func)
rpm-build 2bd099
rpm-build 2bd099
            if self.max_name_len < item.max_name_len:
rpm-build 2bd099
                self.max_name_len = item.max_name_len
rpm-build 2bd099
rpm-build 2bd099
            self.fcn_list = None
rpm-build 2bd099
rpm-build 2bd099
            for func, stat in item.stats.items():
rpm-build 2bd099
                if func in self.stats:
rpm-build 2bd099
                    old_func_stat = self.stats[func]
rpm-build 2bd099
                else:
rpm-build 2bd099
                    old_func_stat = (0, 0, 0, 0, {},)
rpm-build 2bd099
                self.stats[func] = add_func_stats(old_func_stat, stat)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def dump_stats(self, filename):
rpm-build 2bd099
        """Write the profile data to a file we know how to load back."""
rpm-build 2bd099
        with open(filename, 'wb') as f:
rpm-build 2bd099
            marshal.dump(self.stats, f)
rpm-build 2bd099
rpm-build 2bd099
    # list the tuple indices and directions for sorting,
rpm-build 2bd099
    # along with some printable description
rpm-build 2bd099
    sort_arg_dict_default = {
rpm-build 2bd099
              "calls"     : (((1,-1),              ), "call count"),
rpm-build 2bd099
              "ncalls"    : (((1,-1),              ), "call count"),
rpm-build 2bd099
              "cumtime"   : (((3,-1),              ), "cumulative time"),
rpm-build 2bd099
              "cumulative": (((3,-1),              ), "cumulative time"),
rpm-build 2bd099
              "file"      : (((4, 1),              ), "file name"),
rpm-build 2bd099
              "filename"  : (((4, 1),              ), "file name"),
rpm-build 2bd099
              "line"      : (((5, 1),              ), "line number"),
rpm-build 2bd099
              "module"    : (((4, 1),              ), "file name"),
rpm-build 2bd099
              "name"      : (((6, 1),              ), "function name"),
rpm-build 2bd099
              "nfl"       : (((6, 1),(4, 1),(5, 1),), "name/file/line"),
rpm-build 2bd099
              "pcalls"    : (((0,-1),              ), "primitive call count"),
rpm-build 2bd099
              "stdname"   : (((7, 1),              ), "standard name"),
rpm-build 2bd099
              "time"      : (((2,-1),              ), "internal time"),
rpm-build 2bd099
              "tottime"   : (((2,-1),              ), "internal time"),
rpm-build 2bd099
              }
rpm-build 2bd099
rpm-build 2bd099
    def get_sort_arg_defs(self):
rpm-build 2bd099
        """Expand all abbreviations that are unique."""
rpm-build 2bd099
        if not self.sort_arg_dict:
rpm-build 2bd099
            self.sort_arg_dict = dict = {}
rpm-build 2bd099
            bad_list = {}
rpm-build 2bd099
            for word, tup in self.sort_arg_dict_default.items():
rpm-build 2bd099
                fragment = word
rpm-build 2bd099
                while fragment:
rpm-build 2bd099
                    if not fragment:
rpm-build 2bd099
                        break
rpm-build 2bd099
                    if fragment in dict:
rpm-build 2bd099
                        bad_list[fragment] = 0
rpm-build 2bd099
                        break
rpm-build 2bd099
                    dict[fragment] = tup
rpm-build 2bd099
                    fragment = fragment[:-1]
rpm-build 2bd099
            for word in bad_list:
rpm-build 2bd099
                del dict[word]
rpm-build 2bd099
        return self.sort_arg_dict
rpm-build 2bd099
rpm-build 2bd099
    def sort_stats(self, *field):
rpm-build 2bd099
        if not field:
rpm-build 2bd099
            self.fcn_list = 0
rpm-build 2bd099
            return self
rpm-build 2bd099
        if len(field) == 1 and isinstance(field[0], int):
rpm-build 2bd099
            # Be compatible with old profiler
rpm-build 2bd099
            field = [ {-1: "stdname",
rpm-build 2bd099
                       0:  "calls",
rpm-build 2bd099
                       1:  "time",
rpm-build 2bd099
                       2:  "cumulative"}[field[0]] ]
rpm-build 2bd099
rpm-build 2bd099
        sort_arg_defs = self.get_sort_arg_defs()
rpm-build 2bd099
        sort_tuple = ()
rpm-build 2bd099
        self.sort_type = ""
rpm-build 2bd099
        connector = ""
rpm-build 2bd099
        for word in field:
rpm-build 2bd099
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
rpm-build 2bd099
            self.sort_type += connector + sort_arg_defs[word][1]
rpm-build 2bd099
            connector = ", "
rpm-build 2bd099
rpm-build 2bd099
        stats_list = []
rpm-build 2bd099
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
rpm-build 2bd099
            stats_list.append((cc, nc, tt, ct) + func +
rpm-build 2bd099
                              (func_std_string(func), func))
rpm-build 2bd099
rpm-build 2bd099
        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))
rpm-build 2bd099
rpm-build 2bd099
        self.fcn_list = fcn_list = []
rpm-build 2bd099
        for tuple in stats_list:
rpm-build 2bd099
            fcn_list.append(tuple[-1])
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def reverse_order(self):
rpm-build 2bd099
        if self.fcn_list:
rpm-build 2bd099
            self.fcn_list.reverse()
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def strip_dirs(self):
rpm-build 2bd099
        oldstats = self.stats
rpm-build 2bd099
        self.stats = newstats = {}
rpm-build 2bd099
        max_name_len = 0
rpm-build 2bd099
        for func, (cc, nc, tt, ct, callers) in oldstats.items():
rpm-build 2bd099
            newfunc = func_strip_path(func)
rpm-build 2bd099
            if len(func_std_string(newfunc)) > max_name_len:
rpm-build 2bd099
                max_name_len = len(func_std_string(newfunc))
rpm-build 2bd099
            newcallers = {}
rpm-build 2bd099
            for func2, caller in callers.items():
rpm-build 2bd099
                newcallers[func_strip_path(func2)] = caller
rpm-build 2bd099
rpm-build 2bd099
            if newfunc in newstats:
rpm-build 2bd099
                newstats[newfunc] = add_func_stats(
rpm-build 2bd099
                                        newstats[newfunc],
rpm-build 2bd099
                                        (cc, nc, tt, ct, newcallers))
rpm-build 2bd099
            else:
rpm-build 2bd099
                newstats[newfunc] = (cc, nc, tt, ct, newcallers)
rpm-build 2bd099
        old_top = self.top_level
rpm-build 2bd099
        self.top_level = new_top = set()
rpm-build 2bd099
        for func in old_top:
rpm-build 2bd099
            new_top.add(func_strip_path(func))
rpm-build 2bd099
rpm-build 2bd099
        self.max_name_len = max_name_len
rpm-build 2bd099
rpm-build 2bd099
        self.fcn_list = None
rpm-build 2bd099
        self.all_callees = None
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def calc_callees(self):
rpm-build 2bd099
        if self.all_callees:
rpm-build 2bd099
            return
rpm-build 2bd099
        self.all_callees = all_callees = {}
rpm-build 2bd099
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
rpm-build 2bd099
            if not func in all_callees:
rpm-build 2bd099
                all_callees[func] = {}
rpm-build 2bd099
            for func2, caller in callers.items():
rpm-build 2bd099
                if not func2 in all_callees:
rpm-build 2bd099
                    all_callees[func2] = {}
rpm-build 2bd099
                all_callees[func2][func]  = caller
rpm-build 2bd099
        return
rpm-build 2bd099
rpm-build 2bd099
    #******************************************************************
rpm-build 2bd099
    # The following functions support actual printing of reports
rpm-build 2bd099
    #******************************************************************
rpm-build 2bd099
rpm-build 2bd099
    # Optional "amount" is either a line count, or a percentage of lines.
rpm-build 2bd099
rpm-build 2bd099
    def eval_print_amount(self, sel, list, msg):
rpm-build 2bd099
        new_list = list
rpm-build 2bd099
        if isinstance(sel, str):
rpm-build 2bd099
            try:
rpm-build 2bd099
                rex = re.compile(sel)
rpm-build 2bd099
            except re.error:
rpm-build 2bd099
                msg += "   <Invalid regular expression %r>\n" % sel
rpm-build 2bd099
                return new_list, msg
rpm-build 2bd099
            new_list = []
rpm-build 2bd099
            for func in list:
rpm-build 2bd099
                if rex.search(func_std_string(func)):
rpm-build 2bd099
                    new_list.append(func)
rpm-build 2bd099
        else:
rpm-build 2bd099
            count = len(list)
rpm-build 2bd099
            if isinstance(sel, float) and 0.0 <= sel < 1.0:
rpm-build 2bd099
                count = int(count * sel + .5)
rpm-build 2bd099
                new_list = list[:count]
rpm-build 2bd099
            elif isinstance(sel, int) and 0 <= sel < count:
rpm-build 2bd099
                count = sel
rpm-build 2bd099
                new_list = list[:count]
rpm-build 2bd099
        if len(list) != len(new_list):
rpm-build 2bd099
            msg += "   List reduced from %r to %r due to restriction <%r>\n" % (
rpm-build 2bd099
                len(list), len(new_list), sel)
rpm-build 2bd099
rpm-build 2bd099
        return new_list, msg
rpm-build 2bd099
rpm-build 2bd099
    def get_print_list(self, sel_list):
rpm-build 2bd099
        width = self.max_name_len
rpm-build 2bd099
        if self.fcn_list:
rpm-build 2bd099
            stat_list = self.fcn_list[:]
rpm-build 2bd099
            msg = "   Ordered by: " + self.sort_type + '\n'
rpm-build 2bd099
        else:
rpm-build 2bd099
            stat_list = list(self.stats.keys())
rpm-build 2bd099
            msg = "   Random listing order was used\n"
rpm-build 2bd099
rpm-build 2bd099
        for selection in sel_list:
rpm-build 2bd099
            stat_list, msg = self.eval_print_amount(selection, stat_list, msg)
rpm-build 2bd099
rpm-build 2bd099
        count = len(stat_list)
rpm-build 2bd099
rpm-build 2bd099
        if not stat_list:
rpm-build 2bd099
            return 0, stat_list
rpm-build 2bd099
        print(msg, file=self.stream)
rpm-build 2bd099
        if count < len(self.stats):
rpm-build 2bd099
            width = 0
rpm-build 2bd099
            for func in stat_list:
rpm-build 2bd099
                if  len(func_std_string(func)) > width:
rpm-build 2bd099
                    width = len(func_std_string(func))
rpm-build 2bd099
        return width+2, stat_list
rpm-build 2bd099
rpm-build 2bd099
    def print_stats(self, *amount):
rpm-build 2bd099
        for filename in self.files:
rpm-build 2bd099
            print(filename, file=self.stream)
rpm-build 2bd099
        if self.files:
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
        indent = ' ' * 8
rpm-build 2bd099
        for func in self.top_level:
rpm-build 2bd099
            print(indent, func_get_function_name(func), file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
rpm-build 2bd099
        if self.total_calls != self.prim_calls:
rpm-build 2bd099
            print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
rpm-build 2bd099
        print("in %.3f seconds" % self.total_tt, file=self.stream)
rpm-build 2bd099
        print(file=self.stream)
rpm-build 2bd099
        width, list = self.get_print_list(amount)
rpm-build 2bd099
        if list:
rpm-build 2bd099
            self.print_title()
rpm-build 2bd099
            for func in list:
rpm-build 2bd099
                self.print_line(func)
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def print_callees(self, *amount):
rpm-build 2bd099
        width, list = self.get_print_list(amount)
rpm-build 2bd099
        if list:
rpm-build 2bd099
            self.calc_callees()
rpm-build 2bd099
rpm-build 2bd099
            self.print_call_heading(width, "called...")
rpm-build 2bd099
            for func in list:
rpm-build 2bd099
                if func in self.all_callees:
rpm-build 2bd099
                    self.print_call_line(width, func, self.all_callees[func])
rpm-build 2bd099
                else:
rpm-build 2bd099
                    self.print_call_line(width, func, {})
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def print_callers(self, *amount):
rpm-build 2bd099
        width, list = self.get_print_list(amount)
rpm-build 2bd099
        if list:
rpm-build 2bd099
            self.print_call_heading(width, "was called by...")
rpm-build 2bd099
            for func in list:
rpm-build 2bd099
                cc, nc, tt, ct, callers = self.stats[func]
rpm-build 2bd099
                self.print_call_line(width, func, callers, "<-")
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def print_call_heading(self, name_size, column_title):
rpm-build 2bd099
        print("Function ".ljust(name_size) + column_title, file=self.stream)
rpm-build 2bd099
        # print sub-header only if we have new-style callers
rpm-build 2bd099
        subheader = False
rpm-build 2bd099
        for cc, nc, tt, ct, callers in self.stats.values():
rpm-build 2bd099
            if callers:
rpm-build 2bd099
                value = next(iter(callers.values()))
rpm-build 2bd099
                subheader = isinstance(value, tuple)
rpm-build 2bd099
                break
rpm-build 2bd099
        if subheader:
rpm-build 2bd099
            print(" "*name_size + "    ncalls  tottime  cumtime", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
    def print_call_line(self, name_size, source, call_dict, arrow="->"):
rpm-build 2bd099
        print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream)
rpm-build 2bd099
        if not call_dict:
rpm-build 2bd099
            print(file=self.stream)
rpm-build 2bd099
            return
rpm-build 2bd099
        clist = sorted(call_dict.keys())
rpm-build 2bd099
        indent = ""
rpm-build 2bd099
        for func in clist:
rpm-build 2bd099
            name = func_std_string(func)
rpm-build 2bd099
            value = call_dict[func]
rpm-build 2bd099
            if isinstance(value, tuple):
rpm-build 2bd099
                nc, cc, tt, ct = value
rpm-build 2bd099
                if nc != cc:
rpm-build 2bd099
                    substats = '%d/%d' % (nc, cc)
rpm-build 2bd099
                else:
rpm-build 2bd099
                    substats = '%d' % (nc,)
rpm-build 2bd099
                substats = '%s %s %s  %s' % (substats.rjust(7+2*len(indent)),
rpm-build 2bd099
                                             f8(tt), f8(ct), name)
rpm-build 2bd099
                left_width = name_size + 1
rpm-build 2bd099
            else:
rpm-build 2bd099
                substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
rpm-build 2bd099
                left_width = name_size + 3
rpm-build 2bd099
            print(indent*left_width + substats, file=self.stream)
rpm-build 2bd099
            indent = " "
rpm-build 2bd099
rpm-build 2bd099
    def print_title(self):
rpm-build 2bd099
        print('   ncalls  tottime  percall  cumtime  percall', end=' ', file=self.stream)
rpm-build 2bd099
        print('filename:lineno(function)', file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
    def print_line(self, func):  # hack: should print percentages
rpm-build 2bd099
        cc, nc, tt, ct, callers = self.stats[func]
rpm-build 2bd099
        c = str(nc)
rpm-build 2bd099
        if nc != cc:
rpm-build 2bd099
            c = c + '/' + str(cc)
rpm-build 2bd099
        print(c.rjust(9), end=' ', file=self.stream)
rpm-build 2bd099
        print(f8(tt), end=' ', file=self.stream)
rpm-build 2bd099
        if nc == 0:
rpm-build 2bd099
            print(' '*8, end=' ', file=self.stream)
rpm-build 2bd099
        else:
rpm-build 2bd099
            print(f8(tt/nc), end=' ', file=self.stream)
rpm-build 2bd099
        print(f8(ct), end=' ', file=self.stream)
rpm-build 2bd099
        if cc == 0:
rpm-build 2bd099
            print(' '*8, end=' ', file=self.stream)
rpm-build 2bd099
        else:
rpm-build 2bd099
            print(f8(ct/cc), end=' ', file=self.stream)
rpm-build 2bd099
        print(func_std_string(func), file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
class TupleComp:
rpm-build 2bd099
    """This class provides a generic function for comparing any two tuples.
rpm-build 2bd099
    Each instance records a list of tuple-indices (from most significant
rpm-build 2bd099
    to least significant), and sort direction (ascending or decending) for
rpm-build 2bd099
    each tuple-index.  The compare functions can then be used as the function
rpm-build 2bd099
    argument to the system sort() function when a list of tuples need to be
rpm-build 2bd099
    sorted in the instances order."""
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, comp_select_list):
rpm-build 2bd099
        self.comp_select_list = comp_select_list
rpm-build 2bd099
rpm-build 2bd099
    def compare (self, left, right):
rpm-build 2bd099
        for index, direction in self.comp_select_list:
rpm-build 2bd099
            l = left[index]
rpm-build 2bd099
            r = right[index]
rpm-build 2bd099
            if l < r:
rpm-build 2bd099
                return -direction
rpm-build 2bd099
            if l > r:
rpm-build 2bd099
                return direction
rpm-build 2bd099
        return 0
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
# func_name is a triple (file:string, line:int, name:string)
rpm-build 2bd099
rpm-build 2bd099
def func_strip_path(func_name):
rpm-build 2bd099
    filename, line, name = func_name
rpm-build 2bd099
    return os.path.basename(filename), line, name
rpm-build 2bd099
rpm-build 2bd099
def func_get_function_name(func):
rpm-build 2bd099
    return func[2]
rpm-build 2bd099
rpm-build 2bd099
def func_std_string(func_name): # match what old profile produced
rpm-build 2bd099
    if func_name[:2] == ('~', 0):
rpm-build 2bd099
        # special case for built-in functions
rpm-build 2bd099
        name = func_name[2]
rpm-build 2bd099
        if name.startswith('<') and name.endswith('>'):
rpm-build 2bd099
            return '{%s}' % name[1:-1]
rpm-build 2bd099
        else:
rpm-build 2bd099
            return name
rpm-build 2bd099
    else:
rpm-build 2bd099
        return "%s:%d(%s)" % func_name
rpm-build 2bd099
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
# The following functions combine statists for pairs functions.
rpm-build 2bd099
# The bulk of the processing involves correctly handling "call" lists,
rpm-build 2bd099
# such as callers and callees.
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
rpm-build 2bd099
def add_func_stats(target, source):
rpm-build 2bd099
    """Add together all the stats for two profile entries."""
rpm-build 2bd099
    cc, nc, tt, ct, callers = source
rpm-build 2bd099
    t_cc, t_nc, t_tt, t_ct, t_callers = target
rpm-build 2bd099
    return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct,
rpm-build 2bd099
              add_callers(t_callers, callers))
rpm-build 2bd099
rpm-build 2bd099
def add_callers(target, source):
rpm-build 2bd099
    """Combine two caller lists in a single list."""
rpm-build 2bd099
    new_callers = {}
rpm-build 2bd099
    for func, caller in target.items():
rpm-build 2bd099
        new_callers[func] = caller
rpm-build 2bd099
    for func, caller in source.items():
rpm-build 2bd099
        if func in new_callers:
rpm-build 2bd099
            if isinstance(caller, tuple):
rpm-build 2bd099
                # format used by cProfile
rpm-build 2bd099
                new_callers[func] = tuple([i[0] + i[1] for i in
rpm-build 2bd099
                                           zip(caller, new_callers[func])])
rpm-build 2bd099
            else:
rpm-build 2bd099
                # format used by profile
rpm-build 2bd099
                new_callers[func] += caller
rpm-build 2bd099
        else:
rpm-build 2bd099
            new_callers[func] = caller
rpm-build 2bd099
    return new_callers
rpm-build 2bd099
rpm-build 2bd099
def count_calls(callers):
rpm-build 2bd099
    """Sum the caller statistics to get total number of calls received."""
rpm-build 2bd099
    nc = 0
rpm-build 2bd099
    for calls in callers.values():
rpm-build 2bd099
        nc += calls
rpm-build 2bd099
    return nc
rpm-build 2bd099
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
# The following functions support printing of reports
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
rpm-build 2bd099
def f8(x):
rpm-build 2bd099
    return "%8.3f" % x
rpm-build 2bd099
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
# Statistics browser added by ESR, April 2001
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
rpm-build 2bd099
if __name__ == '__main__':
rpm-build 2bd099
    import cmd
rpm-build 2bd099
    try:
rpm-build 2bd099
        import readline
rpm-build 2bd099
    except ImportError:
rpm-build 2bd099
        pass
rpm-build 2bd099
rpm-build 2bd099
    class ProfileBrowser(cmd.Cmd):
rpm-build 2bd099
        def __init__(self, profile=None):
rpm-build 2bd099
            cmd.Cmd.__init__(self)
rpm-build 2bd099
            self.prompt = "% "
rpm-build 2bd099
            self.stats = None
rpm-build 2bd099
            self.stream = sys.stdout
rpm-build 2bd099
            if profile is not None:
rpm-build 2bd099
                self.do_read(profile)
rpm-build 2bd099
rpm-build 2bd099
        def generic(self, fn, line):
rpm-build 2bd099
            args = line.split()
rpm-build 2bd099
            processed = []
rpm-build 2bd099
            for term in args:
rpm-build 2bd099
                try:
rpm-build 2bd099
                    processed.append(int(term))
rpm-build 2bd099
                    continue
rpm-build 2bd099
                except ValueError:
rpm-build 2bd099
                    pass
rpm-build 2bd099
                try:
rpm-build 2bd099
                    frac = float(term)
rpm-build 2bd099
                    if frac > 1 or frac < 0:
rpm-build 2bd099
                        print("Fraction argument must be in [0, 1]", file=self.stream)
rpm-build 2bd099
                        continue
rpm-build 2bd099
                    processed.append(frac)
rpm-build 2bd099
                    continue
rpm-build 2bd099
                except ValueError:
rpm-build 2bd099
                    pass
rpm-build 2bd099
                processed.append(term)
rpm-build 2bd099
            if self.stats:
rpm-build 2bd099
                getattr(self.stats, fn)(*processed)
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("No statistics object is loaded.", file=self.stream)
rpm-build 2bd099
            return 0
rpm-build 2bd099
        def generic_help(self):
rpm-build 2bd099
            print("Arguments may be:", file=self.stream)
rpm-build 2bd099
            print("* An integer maximum number of entries to print.", file=self.stream)
rpm-build 2bd099
            print("* A decimal fractional number between 0 and 1, controlling", file=self.stream)
rpm-build 2bd099
            print("  what fraction of selected entries to print.", file=self.stream)
rpm-build 2bd099
            print("* A regular expression; only entries with function names", file=self.stream)
rpm-build 2bd099
            print("  that match it are printed.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_add(self, line):
rpm-build 2bd099
            if self.stats:
rpm-build 2bd099
                try:
rpm-build 2bd099
                    self.stats.add(line)
rpm-build 2bd099
                except IOError as e:
rpm-build 2bd099
                    print("Failed to load statistics for %s: %s" % (line, e), file=self.stream)
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("No statistics object is loaded.", file=self.stream)
rpm-build 2bd099
            return 0
rpm-build 2bd099
        def help_add(self):
rpm-build 2bd099
            print("Add profile info from given file to current statistics object.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_callees(self, line):
rpm-build 2bd099
            return self.generic('print_callees', line)
rpm-build 2bd099
        def help_callees(self):
rpm-build 2bd099
            print("Print callees statistics from the current stat object.", file=self.stream)
rpm-build 2bd099
            self.generic_help()
rpm-build 2bd099
rpm-build 2bd099
        def do_callers(self, line):
rpm-build 2bd099
            return self.generic('print_callers', line)
rpm-build 2bd099
        def help_callers(self):
rpm-build 2bd099
            print("Print callers statistics from the current stat object.", file=self.stream)
rpm-build 2bd099
            self.generic_help()
rpm-build 2bd099
rpm-build 2bd099
        def do_EOF(self, line):
rpm-build 2bd099
            print("", file=self.stream)
rpm-build 2bd099
            return 1
rpm-build 2bd099
        def help_EOF(self):
rpm-build 2bd099
            print("Leave the profile brower.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_quit(self, line):
rpm-build 2bd099
            return 1
rpm-build 2bd099
        def help_quit(self):
rpm-build 2bd099
            print("Leave the profile brower.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_read(self, line):
rpm-build 2bd099
            if line:
rpm-build 2bd099
                try:
rpm-build 2bd099
                    self.stats = Stats(line)
rpm-build 2bd099
                except OSError as err:
rpm-build 2bd099
                    print(err.args[1], file=self.stream)
rpm-build 2bd099
                    return
rpm-build 2bd099
                except Exception as err:
rpm-build 2bd099
                    print(err.__class__.__name__ + ':', err, file=self.stream)
rpm-build 2bd099
                    return
rpm-build 2bd099
                self.prompt = line + "% "
rpm-build 2bd099
            elif len(self.prompt) > 2:
rpm-build 2bd099
                line = self.prompt[:-2]
rpm-build 2bd099
                self.do_read(line)
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("No statistics object is current -- cannot reload.", file=self.stream)
rpm-build 2bd099
            return 0
rpm-build 2bd099
        def help_read(self):
rpm-build 2bd099
            print("Read in profile data from a specified file.", file=self.stream)
rpm-build 2bd099
            print("Without argument, reload the current file.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_reverse(self, line):
rpm-build 2bd099
            if self.stats:
rpm-build 2bd099
                self.stats.reverse_order()
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("No statistics object is loaded.", file=self.stream)
rpm-build 2bd099
            return 0
rpm-build 2bd099
        def help_reverse(self):
rpm-build 2bd099
            print("Reverse the sort order of the profiling report.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def do_sort(self, line):
rpm-build 2bd099
            if not self.stats:
rpm-build 2bd099
                print("No statistics object is loaded.", file=self.stream)
rpm-build 2bd099
                return
rpm-build 2bd099
            abbrevs = self.stats.get_sort_arg_defs()
rpm-build 2bd099
            if line and all((x in abbrevs) for x in line.split()):
rpm-build 2bd099
                self.stats.sort_stats(*line.split())
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
rpm-build 2bd099
                for (key, value) in Stats.sort_arg_dict_default.items():
rpm-build 2bd099
                    print("%s -- %s" % (key, value[1]), file=self.stream)
rpm-build 2bd099
            return 0
rpm-build 2bd099
        def help_sort(self):
rpm-build 2bd099
            print("Sort profile data according to specified keys.", file=self.stream)
rpm-build 2bd099
            print("(Typing `sort' without arguments lists valid keys.)", file=self.stream)
rpm-build 2bd099
        def complete_sort(self, text, *args):
rpm-build 2bd099
            return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
rpm-build 2bd099
rpm-build 2bd099
        def do_stats(self, line):
rpm-build 2bd099
            return self.generic('print_stats', line)
rpm-build 2bd099
        def help_stats(self):
rpm-build 2bd099
            print("Print statistics from the current stat object.", file=self.stream)
rpm-build 2bd099
            self.generic_help()
rpm-build 2bd099
rpm-build 2bd099
        def do_strip(self, line):
rpm-build 2bd099
            if self.stats:
rpm-build 2bd099
                self.stats.strip_dirs()
rpm-build 2bd099
            else:
rpm-build 2bd099
                print("No statistics object is loaded.", file=self.stream)
rpm-build 2bd099
        def help_strip(self):
rpm-build 2bd099
            print("Strip leading path information from filenames in the report.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def help_help(self):
rpm-build 2bd099
            print("Show help for a given command.", file=self.stream)
rpm-build 2bd099
rpm-build 2bd099
        def postcmd(self, stop, line):
rpm-build 2bd099
            if stop:
rpm-build 2bd099
                return stop
rpm-build 2bd099
            return None
rpm-build 2bd099
rpm-build 2bd099
    if len(sys.argv) > 1:
rpm-build 2bd099
        initprofile = sys.argv[1]
rpm-build 2bd099
    else:
rpm-build 2bd099
        initprofile = None
rpm-build 2bd099
    try:
rpm-build 2bd099
        browser = ProfileBrowser(initprofile)
rpm-build 2bd099
        for profile in sys.argv[2:]:
rpm-build 2bd099
            browser.do_add(profile)
rpm-build 2bd099
        print("Welcome to the profile statistics browser.", file=browser.stream)
rpm-build 2bd099
        browser.cmdloop()
rpm-build 2bd099
        print("Goodbye.", file=browser.stream)
rpm-build 2bd099
    except KeyboardInterrupt:
rpm-build 2bd099
        pass
rpm-build 2bd099
rpm-build 2bd099
# That's all, folks.