Blame Lib/profile.py

rpm-build 2bd099
#! /usr/bin/env python3
rpm-build 2bd099
#
rpm-build 2bd099
# Class for profiling python code. rev 1.0  6/2/94
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
"""Class for profiling Python code."""
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
from optparse import OptionParser
rpm-build 2bd099
rpm-build 2bd099
__all__ = ["run", "runctx", "Profile"]
rpm-build 2bd099
rpm-build 2bd099
# Sample timer for use with
rpm-build 2bd099
#i_count = 0
rpm-build 2bd099
#def integer_timer():
rpm-build 2bd099
#       global i_count
rpm-build 2bd099
#       i_count = i_count + 1
rpm-build 2bd099
#       return i_count
rpm-build 2bd099
#itimes = integer_timer # replace with C coded timer returning integers
rpm-build 2bd099
rpm-build 2bd099
class _Utils:
rpm-build 2bd099
    """Support class for utility functions which are shared by
rpm-build 2bd099
    profile.py and cProfile.py modules.
rpm-build 2bd099
    Not supposed to be used directly.
rpm-build 2bd099
    """
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, profiler):
rpm-build 2bd099
        self.profiler = profiler
rpm-build 2bd099
rpm-build 2bd099
    def run(self, statement, filename, sort):
rpm-build 2bd099
        prof = self.profiler()
rpm-build 2bd099
        try:
rpm-build 2bd099
            prof.run(statement)
rpm-build 2bd099
        except SystemExit:
rpm-build 2bd099
            pass
rpm-build 2bd099
        finally:
rpm-build 2bd099
            self._show(prof, filename, sort)
rpm-build 2bd099
rpm-build 2bd099
    def runctx(self, statement, globals, locals, filename, sort):
rpm-build 2bd099
        prof = self.profiler()
rpm-build 2bd099
        try:
rpm-build 2bd099
            prof.runctx(statement, globals, locals)
rpm-build 2bd099
        except SystemExit:
rpm-build 2bd099
            pass
rpm-build 2bd099
        finally:
rpm-build 2bd099
            self._show(prof, filename, sort)
rpm-build 2bd099
rpm-build 2bd099
    def _show(self, prof, filename, sort):
rpm-build 2bd099
        if filename is not None:
rpm-build 2bd099
            prof.dump_stats(filename)
rpm-build 2bd099
        else:
rpm-build 2bd099
            prof.print_stats(sort)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
# The following are the static member functions for the profiler class
rpm-build 2bd099
# Note that an instance of Profile() is *not* needed to call them.
rpm-build 2bd099
#**************************************************************************
rpm-build 2bd099
rpm-build 2bd099
def run(statement, filename=None, sort=-1):
rpm-build 2bd099
    """Run statement under profiler optionally saving results in filename
rpm-build 2bd099
rpm-build 2bd099
    This function takes a single argument that can be passed to the
rpm-build 2bd099
    "exec" statement, and an optional file name.  In all cases this
rpm-build 2bd099
    routine attempts to "exec" its first argument and gather profiling
rpm-build 2bd099
    statistics from the execution. If no file name is present, then this
rpm-build 2bd099
    function automatically prints a simple profiling report, sorted by the
rpm-build 2bd099
    standard name string (file/line/function-name) that is presented in
rpm-build 2bd099
    each line.
rpm-build 2bd099
    """
rpm-build 2bd099
    return _Utils(Profile).run(statement, filename, sort)
rpm-build 2bd099
rpm-build 2bd099
def runctx(statement, globals, locals, filename=None, sort=-1):
rpm-build 2bd099
    """Run statement under profiler, supplying your own globals and locals,
rpm-build 2bd099
    optionally saving results in filename.
rpm-build 2bd099
rpm-build 2bd099
    statement and filename have the same semantics as profile.run
rpm-build 2bd099
    """
rpm-build 2bd099
    return _Utils(Profile).runctx(statement, globals, locals, filename, sort)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class Profile:
rpm-build 2bd099
    """Profiler class.
rpm-build 2bd099
rpm-build 2bd099
    self.cur is always a tuple.  Each such tuple corresponds to a stack
rpm-build 2bd099
    frame that is currently active (self.cur[-2]).  The following are the
rpm-build 2bd099
    definitions of its members.  We use this external "parallel stack" to
rpm-build 2bd099
    avoid contaminating the program that we are profiling. (old profiler
rpm-build 2bd099
    used to write into the frames local dictionary!!) Derived classes
rpm-build 2bd099
    can change the definition of some entries, as long as they leave
rpm-build 2bd099
    [-2:] intact (frame and previous tuple).  In case an internal error is
rpm-build 2bd099
    detected, the -3 element is used as the function name.
rpm-build 2bd099
rpm-build 2bd099
    [ 0] = Time that needs to be charged to the parent frame's function.
rpm-build 2bd099
           It is used so that a function call will not have to access the
rpm-build 2bd099
           timing data for the parent frame.
rpm-build 2bd099
    [ 1] = Total time spent in this frame's function, excluding time in
rpm-build 2bd099
           subfunctions (this latter is tallied in cur[2]).
rpm-build 2bd099
    [ 2] = Total time spent in subfunctions, excluding time executing the
rpm-build 2bd099
           frame's function (this latter is tallied in cur[1]).
rpm-build 2bd099
    [-3] = Name of the function that corresponds to this frame.
rpm-build 2bd099
    [-2] = Actual frame that we correspond to (used to sync exception handling).
rpm-build 2bd099
    [-1] = Our parent 6-tuple (corresponds to frame.f_back).
rpm-build 2bd099
rpm-build 2bd099
    Timing data for each function is stored as a 5-tuple in the dictionary
rpm-build 2bd099
    self.timings[].  The index is always the name stored in self.cur[-3].
rpm-build 2bd099
    The following are the definitions of the members:
rpm-build 2bd099
rpm-build 2bd099
    [0] = The number of times this function was called, not counting direct
rpm-build 2bd099
          or indirect recursion,
rpm-build 2bd099
    [1] = Number of times this function appears on the stack, minus one
rpm-build 2bd099
    [2] = Total time spent internal to this function
rpm-build 2bd099
    [3] = Cumulative time that this function was present on the stack.  In
rpm-build 2bd099
          non-recursive functions, this is the total execution time from start
rpm-build 2bd099
          to finish of each invocation of a function, including time spent in
rpm-build 2bd099
          all subfunctions.
rpm-build 2bd099
    [4] = A dictionary indicating for each function name, the number of times
rpm-build 2bd099
          it was called by us.
rpm-build 2bd099
    """
rpm-build 2bd099
rpm-build 2bd099
    bias = 0  # calibration constant
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, timer=None, bias=None):
rpm-build 2bd099
        self.timings = {}
rpm-build 2bd099
        self.cur = None
rpm-build 2bd099
        self.cmd = ""
rpm-build 2bd099
        self.c_func_name = ""
rpm-build 2bd099
rpm-build 2bd099
        if bias is None:
rpm-build 2bd099
            bias = self.bias
rpm-build 2bd099
        self.bias = bias     # Materialize in local dict for lookup speed.
rpm-build 2bd099
rpm-build 2bd099
        if not timer:
rpm-build 2bd099
            self.timer = self.get_time = time.process_time
rpm-build 2bd099
            self.dispatcher = self.trace_dispatch_i
rpm-build 2bd099
        else:
rpm-build 2bd099
            self.timer = timer
rpm-build 2bd099
            t = self.timer() # test out timer function
rpm-build 2bd099
            try:
rpm-build 2bd099
                length = len(t)
rpm-build 2bd099
            except TypeError:
rpm-build 2bd099
                self.get_time = timer
rpm-build 2bd099
                self.dispatcher = self.trace_dispatch_i
rpm-build 2bd099
            else:
rpm-build 2bd099
                if length == 2:
rpm-build 2bd099
                    self.dispatcher = self.trace_dispatch
rpm-build 2bd099
                else:
rpm-build 2bd099
                    self.dispatcher = self.trace_dispatch_l
rpm-build 2bd099
                # This get_time() implementation needs to be defined
rpm-build 2bd099
                # here to capture the passed-in timer in the parameter
rpm-build 2bd099
                # list (for performance).  Note that we can't assume
rpm-build 2bd099
                # the timer() result contains two values in all
rpm-build 2bd099
                # cases.
rpm-build 2bd099
                def get_time_timer(timer=timer, sum=sum):
rpm-build 2bd099
                    return sum(timer())
rpm-build 2bd099
                self.get_time = get_time_timer
rpm-build 2bd099
        self.t = self.get_time()
rpm-build 2bd099
        self.simulate_call('profiler')
rpm-build 2bd099
rpm-build 2bd099
    # Heavily optimized dispatch routine for os.times() timer
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch(self, frame, event, arg):
rpm-build 2bd099
        timer = self.timer
rpm-build 2bd099
        t = timer()
rpm-build 2bd099
        t = t[0] + t[1] - self.t - self.bias
rpm-build 2bd099
rpm-build 2bd099
        if event == "c_call":
rpm-build 2bd099
            self.c_func_name = arg.__name__
rpm-build 2bd099
rpm-build 2bd099
        if self.dispatch[event](self, frame,t):
rpm-build 2bd099
            t = timer()
rpm-build 2bd099
            self.t = t[0] + t[1]
rpm-build 2bd099
        else:
rpm-build 2bd099
            r = timer()
rpm-build 2bd099
            self.t = r[0] + r[1] - t # put back unrecorded delta
rpm-build 2bd099
rpm-build 2bd099
    # Dispatch routine for best timer program (return = scalar, fastest if
rpm-build 2bd099
    # an integer but float works too -- and time.clock() relies on that).
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_i(self, frame, event, arg):
rpm-build 2bd099
        timer = self.timer
rpm-build 2bd099
        t = timer() - self.t - self.bias
rpm-build 2bd099
rpm-build 2bd099
        if event == "c_call":
rpm-build 2bd099
            self.c_func_name = arg.__name__
rpm-build 2bd099
rpm-build 2bd099
        if self.dispatch[event](self, frame, t):
rpm-build 2bd099
            self.t = timer()
rpm-build 2bd099
        else:
rpm-build 2bd099
            self.t = timer() - t  # put back unrecorded delta
rpm-build 2bd099
rpm-build 2bd099
    # Dispatch routine for macintosh (timer returns time in ticks of
rpm-build 2bd099
    # 1/60th second)
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_mac(self, frame, event, arg):
rpm-build 2bd099
        timer = self.timer
rpm-build 2bd099
        t = timer()/60.0 - self.t - self.bias
rpm-build 2bd099
rpm-build 2bd099
        if event == "c_call":
rpm-build 2bd099
            self.c_func_name = arg.__name__
rpm-build 2bd099
rpm-build 2bd099
        if self.dispatch[event](self, frame, t):
rpm-build 2bd099
            self.t = timer()/60.0
rpm-build 2bd099
        else:
rpm-build 2bd099
            self.t = timer()/60.0 - t  # put back unrecorded delta
rpm-build 2bd099
rpm-build 2bd099
    # SLOW generic dispatch routine for timer returning lists of numbers
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_l(self, frame, event, arg):
rpm-build 2bd099
        get_time = self.get_time
rpm-build 2bd099
        t = get_time() - self.t - self.bias
rpm-build 2bd099
rpm-build 2bd099
        if event == "c_call":
rpm-build 2bd099
            self.c_func_name = arg.__name__
rpm-build 2bd099
rpm-build 2bd099
        if self.dispatch[event](self, frame, t):
rpm-build 2bd099
            self.t = get_time()
rpm-build 2bd099
        else:
rpm-build 2bd099
            self.t = get_time() - t # put back unrecorded delta
rpm-build 2bd099
rpm-build 2bd099
    # In the event handlers, the first 3 elements of self.cur are unpacked
rpm-build 2bd099
    # into vrbls w/ 3-letter names.  The last two characters are meant to be
rpm-build 2bd099
    # mnemonic:
rpm-build 2bd099
    #     _pt  self.cur[0] "parent time"   time to be charged to parent frame
rpm-build 2bd099
    #     _it  self.cur[1] "internal time" time spent directly in the function
rpm-build 2bd099
    #     _et  self.cur[2] "external time" time spent in subfunctions
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_exception(self, frame, t):
rpm-build 2bd099
        rpt, rit, ret, rfn, rframe, rcur = self.cur
rpm-build 2bd099
        if (rframe is not frame) and rcur:
rpm-build 2bd099
            return self.trace_dispatch_return(rframe, t)
rpm-build 2bd099
        self.cur = rpt, rit+t, ret, rfn, rframe, rcur
rpm-build 2bd099
        return 1
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_call(self, frame, t):
rpm-build 2bd099
        if self.cur and frame.f_back is not self.cur[-2]:
rpm-build 2bd099
            rpt, rit, ret, rfn, rframe, rcur = self.cur
rpm-build 2bd099
            if not isinstance(rframe, Profile.fake_frame):
rpm-build 2bd099
                assert rframe.f_back is frame.f_back, ("Bad call", rfn,
rpm-build 2bd099
                                                       rframe, rframe.f_back,
rpm-build 2bd099
                                                       frame, frame.f_back)
rpm-build 2bd099
                self.trace_dispatch_return(rframe, 0)
rpm-build 2bd099
                assert (self.cur is None or \
rpm-build 2bd099
                        frame.f_back is self.cur[-2]), ("Bad call",
rpm-build 2bd099
                                                        self.cur[-3])
rpm-build 2bd099
        fcode = frame.f_code
rpm-build 2bd099
        fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
rpm-build 2bd099
        self.cur = (t, 0, 0, fn, frame, self.cur)
rpm-build 2bd099
        timings = self.timings
rpm-build 2bd099
        if fn in timings:
rpm-build 2bd099
            cc, ns, tt, ct, callers = timings[fn]
rpm-build 2bd099
            timings[fn] = cc, ns + 1, tt, ct, callers
rpm-build 2bd099
        else:
rpm-build 2bd099
            timings[fn] = 0, 0, 0, 0, {}
rpm-build 2bd099
        return 1
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_c_call (self, frame, t):
rpm-build 2bd099
        fn = ("", 0, self.c_func_name)
rpm-build 2bd099
        self.cur = (t, 0, 0, fn, frame, self.cur)
rpm-build 2bd099
        timings = self.timings
rpm-build 2bd099
        if fn in timings:
rpm-build 2bd099
            cc, ns, tt, ct, callers = timings[fn]
rpm-build 2bd099
            timings[fn] = cc, ns+1, tt, ct, callers
rpm-build 2bd099
        else:
rpm-build 2bd099
            timings[fn] = 0, 0, 0, 0, {}
rpm-build 2bd099
        return 1
rpm-build 2bd099
rpm-build 2bd099
    def trace_dispatch_return(self, frame, t):
rpm-build 2bd099
        if frame is not self.cur[-2]:
rpm-build 2bd099
            assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3])
rpm-build 2bd099
            self.trace_dispatch_return(self.cur[-2], 0)
rpm-build 2bd099
rpm-build 2bd099
        # Prefix "r" means part of the Returning or exiting frame.
rpm-build 2bd099
        # Prefix "p" means part of the Previous or Parent or older frame.
rpm-build 2bd099
rpm-build 2bd099
        rpt, rit, ret, rfn, frame, rcur = self.cur
rpm-build 2bd099
        rit = rit + t
rpm-build 2bd099
        frame_total = rit + ret
rpm-build 2bd099
rpm-build 2bd099
        ppt, pit, pet, pfn, pframe, pcur = rcur
rpm-build 2bd099
        self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur
rpm-build 2bd099
rpm-build 2bd099
        timings = self.timings
rpm-build 2bd099
        cc, ns, tt, ct, callers = timings[rfn]
rpm-build 2bd099
        if not ns:
rpm-build 2bd099
            # This is the only occurrence of the function on the stack.
rpm-build 2bd099
            # Else this is a (directly or indirectly) recursive call, and
rpm-build 2bd099
            # its cumulative time will get updated when the topmost call to
rpm-build 2bd099
            # it returns.
rpm-build 2bd099
            ct = ct + frame_total
rpm-build 2bd099
            cc = cc + 1
rpm-build 2bd099
rpm-build 2bd099
        if pfn in callers:
rpm-build 2bd099
            callers[pfn] = callers[pfn] + 1  # hack: gather more
rpm-build 2bd099
            # stats such as the amount of time added to ct courtesy
rpm-build 2bd099
            # of this specific call, and the contribution to cc
rpm-build 2bd099
            # courtesy of this call.
rpm-build 2bd099
        else:
rpm-build 2bd099
            callers[pfn] = 1
rpm-build 2bd099
rpm-build 2bd099
        timings[rfn] = cc, ns - 1, tt + rit, ct, callers
rpm-build 2bd099
rpm-build 2bd099
        return 1
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    dispatch = {
rpm-build 2bd099
        "call": trace_dispatch_call,
rpm-build 2bd099
        "exception": trace_dispatch_exception,
rpm-build 2bd099
        "return": trace_dispatch_return,
rpm-build 2bd099
        "c_call": trace_dispatch_c_call,
rpm-build 2bd099
        "c_exception": trace_dispatch_return,  # the C function returned
rpm-build 2bd099
        "c_return": trace_dispatch_return,
rpm-build 2bd099
        }
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    # The next few functions play with self.cmd. By carefully preloading
rpm-build 2bd099
    # our parallel stack, we can force the profiled result to include
rpm-build 2bd099
    # an arbitrary string as the name of the calling function.
rpm-build 2bd099
    # We use self.cmd as that string, and the resulting stats look
rpm-build 2bd099
    # very nice :-).
rpm-build 2bd099
rpm-build 2bd099
    def set_cmd(self, cmd):
rpm-build 2bd099
        if self.cur[-1]: return   # already set
rpm-build 2bd099
        self.cmd = cmd
rpm-build 2bd099
        self.simulate_call(cmd)
rpm-build 2bd099
rpm-build 2bd099
    class fake_code:
rpm-build 2bd099
        def __init__(self, filename, line, name):
rpm-build 2bd099
            self.co_filename = filename
rpm-build 2bd099
            self.co_line = line
rpm-build 2bd099
            self.co_name = name
rpm-build 2bd099
            self.co_firstlineno = 0
rpm-build 2bd099
rpm-build 2bd099
        def __repr__(self):
rpm-build 2bd099
            return repr((self.co_filename, self.co_line, self.co_name))
rpm-build 2bd099
rpm-build 2bd099
    class fake_frame:
rpm-build 2bd099
        def __init__(self, code, prior):
rpm-build 2bd099
            self.f_code = code
rpm-build 2bd099
            self.f_back = prior
rpm-build 2bd099
rpm-build 2bd099
    def simulate_call(self, name):
rpm-build 2bd099
        code = self.fake_code('profile', 0, name)
rpm-build 2bd099
        if self.cur:
rpm-build 2bd099
            pframe = self.cur[-2]
rpm-build 2bd099
        else:
rpm-build 2bd099
            pframe = None
rpm-build 2bd099
        frame = self.fake_frame(code, pframe)
rpm-build 2bd099
        self.dispatch['call'](self, frame, 0)
rpm-build 2bd099
rpm-build 2bd099
    # collect stats from pending stack, including getting final
rpm-build 2bd099
    # timings for self.cmd frame.
rpm-build 2bd099
rpm-build 2bd099
    def simulate_cmd_complete(self):
rpm-build 2bd099
        get_time = self.get_time
rpm-build 2bd099
        t = get_time() - self.t
rpm-build 2bd099
        while self.cur[-1]:
rpm-build 2bd099
            # We *can* cause assertion errors here if
rpm-build 2bd099
            # dispatch_trace_return checks for a frame match!
rpm-build 2bd099
            self.dispatch['return'](self, self.cur[-2], t)
rpm-build 2bd099
            t = 0
rpm-build 2bd099
        self.t = get_time() - t
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    def print_stats(self, sort=-1):
rpm-build 2bd099
        import pstats
rpm-build 2bd099
        pstats.Stats(self).strip_dirs().sort_stats(sort). \
rpm-build 2bd099
                  print_stats()
rpm-build 2bd099
rpm-build 2bd099
    def dump_stats(self, file):
rpm-build 2bd099
        with open(file, 'wb') as f:
rpm-build 2bd099
            self.create_stats()
rpm-build 2bd099
            marshal.dump(self.stats, f)
rpm-build 2bd099
rpm-build 2bd099
    def create_stats(self):
rpm-build 2bd099
        self.simulate_cmd_complete()
rpm-build 2bd099
        self.snapshot_stats()
rpm-build 2bd099
rpm-build 2bd099
    def snapshot_stats(self):
rpm-build 2bd099
        self.stats = {}
rpm-build 2bd099
        for func, (cc, ns, tt, ct, callers) in self.timings.items():
rpm-build 2bd099
            callers = callers.copy()
rpm-build 2bd099
            nc = 0
rpm-build 2bd099
            for callcnt in callers.values():
rpm-build 2bd099
                nc += callcnt
rpm-build 2bd099
            self.stats[func] = cc, nc, tt, ct, callers
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    # The following two methods can be called by clients to use
rpm-build 2bd099
    # a profiler to profile a statement, given as a string.
rpm-build 2bd099
rpm-build 2bd099
    def run(self, cmd):
rpm-build 2bd099
        import __main__
rpm-build 2bd099
        dict = __main__.__dict__
rpm-build 2bd099
        return self.runctx(cmd, dict, dict)
rpm-build 2bd099
rpm-build 2bd099
    def runctx(self, cmd, globals, locals):
rpm-build 2bd099
        self.set_cmd(cmd)
rpm-build 2bd099
        sys.setprofile(self.dispatcher)
rpm-build 2bd099
        try:
rpm-build 2bd099
            exec(cmd, globals, locals)
rpm-build 2bd099
        finally:
rpm-build 2bd099
            sys.setprofile(None)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    # This method is more useful to profile a single function call.
rpm-build 2bd099
    def runcall(self, func, *args, **kw):
rpm-build 2bd099
        self.set_cmd(repr(func))
rpm-build 2bd099
        sys.setprofile(self.dispatcher)
rpm-build 2bd099
        try:
rpm-build 2bd099
            return func(*args, **kw)
rpm-build 2bd099
        finally:
rpm-build 2bd099
            sys.setprofile(None)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
    #******************************************************************
rpm-build 2bd099
    # The following calculates the overhead for using a profiler.  The
rpm-build 2bd099
    # problem is that it takes a fair amount of time for the profiler
rpm-build 2bd099
    # to stop the stopwatch (from the time it receives an event).
rpm-build 2bd099
    # Similarly, there is a delay from the time that the profiler
rpm-build 2bd099
    # re-starts the stopwatch before the user's code really gets to
rpm-build 2bd099
    # continue.  The following code tries to measure the difference on
rpm-build 2bd099
    # a per-event basis.
rpm-build 2bd099
    #
rpm-build 2bd099
    # Note that this difference is only significant if there are a lot of
rpm-build 2bd099
    # events, and relatively little user code per event.  For example,
rpm-build 2bd099
    # code with small functions will typically benefit from having the
rpm-build 2bd099
    # profiler calibrated for the current platform.  This *could* be
rpm-build 2bd099
    # done on the fly during init() time, but it is not worth the
rpm-build 2bd099
    # effort.  Also note that if too large a value specified, then
rpm-build 2bd099
    # execution time on some functions will actually appear as a
rpm-build 2bd099
    # negative number.  It is *normal* for some functions (with very
rpm-build 2bd099
    # low call counts) to have such negative stats, even if the
rpm-build 2bd099
    # calibration figure is "correct."
rpm-build 2bd099
    #
rpm-build 2bd099
    # One alternative to profile-time calibration adjustments (i.e.,
rpm-build 2bd099
    # adding in the magic little delta during each event) is to track
rpm-build 2bd099
    # more carefully the number of events (and cumulatively, the number
rpm-build 2bd099
    # of events during sub functions) that are seen.  If this were
rpm-build 2bd099
    # done, then the arithmetic could be done after the fact (i.e., at
rpm-build 2bd099
    # display time).  Currently, we track only call/return events.
rpm-build 2bd099
    # These values can be deduced by examining the callees and callers
rpm-build 2bd099
    # vectors for each functions.  Hence we *can* almost correct the
rpm-build 2bd099
    # internal time figure at print time (note that we currently don't
rpm-build 2bd099
    # track exception event processing counts).  Unfortunately, there
rpm-build 2bd099
    # is currently no similar information for cumulative sub-function
rpm-build 2bd099
    # time.  It would not be hard to "get all this info" at profiler
rpm-build 2bd099
    # time.  Specifically, we would have to extend the tuples to keep
rpm-build 2bd099
    # counts of this in each frame, and then extend the defs of timing
rpm-build 2bd099
    # tuples to include the significant two figures. I'm a bit fearful
rpm-build 2bd099
    # that this additional feature will slow the heavily optimized
rpm-build 2bd099
    # event/time ratio (i.e., the profiler would run slower, fur a very
rpm-build 2bd099
    # low "value added" feature.)
rpm-build 2bd099
    #**************************************************************
rpm-build 2bd099
rpm-build 2bd099
    def calibrate(self, m, verbose=0):
rpm-build 2bd099
        if self.__class__ is not Profile:
rpm-build 2bd099
            raise TypeError("Subclasses must override .calibrate().")
rpm-build 2bd099
rpm-build 2bd099
        saved_bias = self.bias
rpm-build 2bd099
        self.bias = 0
rpm-build 2bd099
        try:
rpm-build 2bd099
            return self._calibrate_inner(m, verbose)
rpm-build 2bd099
        finally:
rpm-build 2bd099
            self.bias = saved_bias
rpm-build 2bd099
rpm-build 2bd099
    def _calibrate_inner(self, m, verbose):
rpm-build 2bd099
        get_time = self.get_time
rpm-build 2bd099
rpm-build 2bd099
        # Set up a test case to be run with and without profiling.  Include
rpm-build 2bd099
        # lots of calls, because we're trying to quantify stopwatch overhead.
rpm-build 2bd099
        # Do not raise any exceptions, though, because we want to know
rpm-build 2bd099
        # exactly how many profile events are generated (one call event, +
rpm-build 2bd099
        # one return event, per Python-level call).
rpm-build 2bd099
rpm-build 2bd099
        def f1(n):
rpm-build 2bd099
            for i in range(n):
rpm-build 2bd099
                x = 1
rpm-build 2bd099
rpm-build 2bd099
        def f(m, f1=f1):
rpm-build 2bd099
            for i in range(m):
rpm-build 2bd099
                f1(100)
rpm-build 2bd099
rpm-build 2bd099
        f(m)    # warm up the cache
rpm-build 2bd099
rpm-build 2bd099
        # elapsed_noprofile <- time f(m) takes without profiling.
rpm-build 2bd099
        t0 = get_time()
rpm-build 2bd099
        f(m)
rpm-build 2bd099
        t1 = get_time()
rpm-build 2bd099
        elapsed_noprofile = t1 - t0
rpm-build 2bd099
        if verbose:
rpm-build 2bd099
            print("elapsed time without profiling =", elapsed_noprofile)
rpm-build 2bd099
rpm-build 2bd099
        # elapsed_profile <- time f(m) takes with profiling.  The difference
rpm-build 2bd099
        # is profiling overhead, only some of which the profiler subtracts
rpm-build 2bd099
        # out on its own.
rpm-build 2bd099
        p = Profile()
rpm-build 2bd099
        t0 = get_time()
rpm-build 2bd099
        p.runctx('f(m)', globals(), locals())
rpm-build 2bd099
        t1 = get_time()
rpm-build 2bd099
        elapsed_profile = t1 - t0
rpm-build 2bd099
        if verbose:
rpm-build 2bd099
            print("elapsed time with profiling =", elapsed_profile)
rpm-build 2bd099
rpm-build 2bd099
        # reported_time <- "CPU seconds" the profiler charged to f and f1.
rpm-build 2bd099
        total_calls = 0.0
rpm-build 2bd099
        reported_time = 0.0
rpm-build 2bd099
        for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
rpm-build 2bd099
                p.timings.items():
rpm-build 2bd099
            if funcname in ("f", "f1"):
rpm-build 2bd099
                total_calls += cc
rpm-build 2bd099
                reported_time += tt
rpm-build 2bd099
rpm-build 2bd099
        if verbose:
rpm-build 2bd099
            print("'CPU seconds' profiler reported =", reported_time)
rpm-build 2bd099
            print("total # calls =", total_calls)
rpm-build 2bd099
        if total_calls != m + 1:
rpm-build 2bd099
            raise ValueError("internal error: total calls = %d" % total_calls)
rpm-build 2bd099
rpm-build 2bd099
        # reported_time - elapsed_noprofile = overhead the profiler wasn't
rpm-build 2bd099
        # able to measure.  Divide by twice the number of calls (since there
rpm-build 2bd099
        # are two profiler events per call in this test) to get the hidden
rpm-build 2bd099
        # overhead per event.
rpm-build 2bd099
        mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
rpm-build 2bd099
        if verbose:
rpm-build 2bd099
            print("mean stopwatch overhead per profile event =", mean)
rpm-build 2bd099
        return mean
rpm-build 2bd099
rpm-build 2bd099
#****************************************************************************
rpm-build 2bd099
rpm-build 2bd099
def main():
rpm-build 2bd099
    usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
rpm-build 2bd099
    parser = OptionParser(usage=usage)
rpm-build 2bd099
    parser.allow_interspersed_args = False
rpm-build 2bd099
    parser.add_option('-o', '--outfile', dest="outfile",
rpm-build 2bd099
        help="Save stats to <outfile>", default=None)
rpm-build 2bd099
    parser.add_option('-s', '--sort', dest="sort",
rpm-build 2bd099
        help="Sort order when printing to stdout, based on pstats.Stats class",
rpm-build 2bd099
        default=-1)
rpm-build 2bd099
rpm-build 2bd099
    if not sys.argv[1:]:
rpm-build 2bd099
        parser.print_usage()
rpm-build 2bd099
        sys.exit(2)
rpm-build 2bd099
rpm-build 2bd099
    (options, args) = parser.parse_args()
rpm-build 2bd099
    sys.argv[:] = args
rpm-build 2bd099
rpm-build 2bd099
    if len(args) > 0:
rpm-build 2bd099
        progname = args[0]
rpm-build 2bd099
        sys.path.insert(0, os.path.dirname(progname))
rpm-build 2bd099
        with open(progname, 'rb') as fp:
rpm-build 2bd099
            code = compile(fp.read(), progname, 'exec')
rpm-build 2bd099
        globs = {
rpm-build 2bd099
            '__file__': progname,
rpm-build 2bd099
            '__name__': '__main__',
rpm-build 2bd099
            '__package__': None,
rpm-build 2bd099
            '__cached__': None,
rpm-build 2bd099
        }
rpm-build 2bd099
        runctx(code, globs, None, options.outfile, options.sort)
rpm-build 2bd099
    else:
rpm-build 2bd099
        parser.print_usage()
rpm-build 2bd099
    return parser
rpm-build 2bd099
rpm-build 2bd099
# When invoked as main program, invoke the profiler on a script
rpm-build 2bd099
if __name__ == '__main__':
rpm-build 2bd099
    main()