home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Python 1.1 / Lib / profile.py < prev    next >
Encoding:
Text File  |  1994-08-01  |  19.8 KB  |  613 lines  |  [TEXT/R*ch]

  1. #
  2. # Class for profiling python code. rev 1.0  6/2/94
  3. #
  4. # Based on prior profile module by Sjoerd Mullender...
  5. #   which was hacked somewhat by: Guido van Rossum
  6. #
  7. # See profile.doc for more information
  8.  
  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.  
  34. import sys
  35. import os
  36. import time
  37. import string
  38. import marshal
  39.  
  40.  
  41. # Global variables
  42. func_norm_dict = {}
  43. func_norm_counter = 0
  44. pid_string = `os.getpid()`
  45.  
  46.  
  47. # Optimized intermodule references
  48. ostimes = os.times
  49.  
  50.  
  51. # Sample timer for use with 
  52. #i_count = 0
  53. #def integer_timer():
  54. #    global i_count
  55. #    i_count = i_count + 1
  56. #    return i_count
  57. #itimes = integer_timer # replace with C coded timer returning integers
  58.  
  59. #**************************************************************************
  60. # The following are the static member functions for the profiler class
  61. # Note that an instance of Profile() is *not* needed to call them.
  62. #**************************************************************************
  63.  
  64.  
  65. # simplified user interface
  66. def run(statement, *args):
  67.     prof = Profile()
  68.     try:
  69.         prof = prof.run(statement)
  70.     except SystemExit:
  71.         pass
  72.     if args:
  73.         prof.dump_stats(args[0])
  74.     else:
  75.         return prof.print_stats()
  76.  
  77. # print help
  78. def help():
  79.     for dirname in sys.path:
  80.         fullname = os.path.join(dirname, 'profile.doc')
  81.         if os.path.exists(fullname):
  82.             sts = os.system('${PAGER-more} '+fullname)
  83.             if sts: print '*** Pager exit status:', sts
  84.             break
  85.     else:
  86.         print 'Sorry, can\'t find the help file "profile.doc"',
  87.         print 'along the Python search path'
  88.  
  89.  
  90. #**************************************************************************
  91. # class Profile documentation:
  92. #**************************************************************************
  93. # self.cur is always a tuple.  Each such tuple corresponds to a stack
  94. # frame that is currently active (self.cur[-2]).  The following are the
  95. # definitions of its members.  We use this external "parallel stack" to
  96. # avoid contaminating the program that we are profiling. (old profiler
  97. # used to write into the frames local dictionary!!) Derived classes
  98. # can change the definition of some entries, as long as they leave
  99. # [-2:] intact.
  100. #
  101. # [ 0] = Time that needs to be charged to the parent frame's function.  It is
  102. #        used so that a function call will not have to access the timing data
  103. #        for the parents frame.
  104. # [ 1] = Total time spent in this frame's function, excluding time in
  105. #        subfunctions
  106. # [ 2] = Cumulative time spent in this frame's function, including time in
  107. #        all subfunctions to this frame.
  108. # [-3] = Name of the function that corresonds to this frame.  
  109. # [-2] = Actual frame that we correspond to (used to sync exception handling)
  110. # [-1] = Our parent 6-tuple (corresonds to frame.f_back)
  111. #**************************************************************************
  112. # Timing data for each function is stored as a 5-tuple in the dictionary
  113. # self.timings[].  The index is always the name stored in self.cur[4].
  114. # The following are the definitions of the members:
  115. #
  116. # [0] = The number of times this function was called, not counting direct
  117. #       or indirect recursion,
  118. # [1] = Number of times this function appears on the stack, minus one
  119. # [2] = Total time spent internal to this function
  120. # [3] = Cumulative time that this function was present on the stack.  In
  121. #       non-recursive functions, this is the total execution time from start
  122. #       to finish of each invocation of a function, including time spent in
  123. #       all subfunctions.
  124. # [5] = A dictionary indicating for each function name, the number of times
  125. #       it was called by us.
  126. #**************************************************************************
  127. # We produce function names via a repr() call on the f_code object during
  128. # profiling. This save a *lot* of CPU time.  This results in a string that
  129. # always looks like:
  130. #   <code object main at 87090, file "/a/lib/python-local/myfib.py", line 76>
  131. # After we "normalize it, it is a tuple of filename, line, function-name.
  132. # We wait till we are done profiling to do the normalization.
  133. # *IF* this repr format changes, then only the normalization routine should
  134. # need to be fixed.
  135. #**************************************************************************
  136. class Profile:
  137.  
  138.     def __init__(self, *arg):
  139.         self.timings = {}
  140.         self.cur = None
  141.         self.cmd = ""
  142.  
  143.         self.dispatch = {  \
  144.               'call'     : self.trace_dispatch_call, \
  145.               'return'   : self.trace_dispatch_return, \
  146.               'exception': self.trace_dispatch_exception, \
  147.               }
  148.  
  149.         if not arg:
  150.             self.timer = os.times
  151.             self.dispatcher = self.trace_dispatch
  152.         else:
  153.             self.timer = arg[0]
  154.             t = self.timer() # test out timer function
  155.             try:
  156.                 if len(t) == 2:
  157.                     self.dispatcher = self.trace_dispatch
  158.                 else:
  159.                     self.dispatcher = self.trace_dispatch_r
  160.             except:
  161.                 self.dispatcher = self.trace_dispatch_i
  162.         self.t = self.get_time()
  163.         self.simulate_call('profiler')
  164.  
  165.  
  166.     def get_time(self): # slow simulation of method to acquire time
  167.         t = self.timer()
  168.         if type(t) == type(()) or type(t) == type([]):
  169.             t = reduce(lambda x,y: x+y, t, 0)
  170.         return t
  171.         
  172.  
  173.     # Heavily optimized dispatch routine for os.times() timer
  174.  
  175.     def trace_dispatch(self, frame, event, arg):
  176.         t = self.timer()
  177.         t = t[0] + t[1] - self.t        # No Calibration constant
  178.         # t = t[0] + t[1] - self.t - .00053 # Calibration constant
  179.  
  180.         if self.dispatch[event](frame,t):
  181.             t = self.timer()
  182.             self.t = t[0] + t[1]
  183.         else:
  184.             r = self.timer()
  185.             self.t = r[0] + r[1] - t # put back unrecorded delta
  186.         return
  187.  
  188.  
  189.  
  190.     # Dispatch routine for best timer program (return = scalar integer)
  191.  
  192.     def trace_dispatch_i(self, frame, event, arg):
  193.         t = self.timer() - self.t # - 1 # Integer calibration constant
  194.         if self.dispatch[event](frame,t):
  195.             self.t = self.timer()
  196.         else:
  197.             self.t = self.timer() - t  # put back unrecorded delta
  198.         return
  199.  
  200.  
  201.     # SLOW generic dispatch rountine for timer returning lists of numbers
  202.  
  203.     def trace_dispatch_l(self, frame, event, arg):
  204.         t = self.get_time() - self.t
  205.  
  206.         if self.dispatch[event](frame,t):
  207.             self.t = self.get_time()
  208.         else:
  209.             self.t = self.get_time()-t # put back unrecorded delta
  210.         return
  211.  
  212.  
  213.     def trace_dispatch_exception(self, frame, t):
  214.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  215.         if (not rframe is frame) and rcur:
  216.             return self.trace_dispatch_return(rframe, t)
  217.         return 0
  218.  
  219.  
  220.     def trace_dispatch_call(self, frame, t):
  221.         fn = `frame.f_code` 
  222.  
  223.         # The following should be about the best approach, but
  224.         # we would need a function that maps from id() back to
  225.         # the actual code object.  
  226.         #     fn = id(frame.f_code)
  227.         # Note we would really use our own function, which would
  228.         # return the code address, *and* bump the ref count.  We
  229.         # would then fix up the normalize function to do the
  230.         # actualy repr(fn) call.
  231.  
  232.         # The following is an interesting alternative
  233.         # It doesn't do as good a job, and it doesn't run as
  234.         # fast 'cause repr() is written in C, and this is Python.
  235.         #fcode = frame.f_code
  236.         #code = fcode.co_code
  237.         #if ord(code[0]) == 127: #  == SET_LINENO
  238.         #    # see "opcode.h" in the Python source
  239.         #    fn = (fcode.co_filename, ord(code[1]) | \
  240.         #          ord(code[2]) << 8, fcode.co_name)
  241.         #else:
  242.         #    fn = (fcode.co_filename, 0, fcode.co_name)
  243.  
  244.         self.cur = (t, 0, 0, fn, frame, self.cur)
  245.         if self.timings.has_key(fn):
  246.             cc, ns, tt, ct, callers = self.timings[fn]
  247.             self.timings[fn] = cc, ns + 1, tt, ct, callers
  248.         else:
  249.             self.timings[fn] = 0, 0, 0, 0, {}
  250.         return 1
  251.  
  252.     def trace_dispatch_return(self, frame, t):
  253.         # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
  254.  
  255.         # Prefix "r" means part of the Returning or exiting frame
  256.         # Prefix "p" means part of the Previous or older frame
  257.  
  258.         rt, rtt, rct, rfn, frame, rcur = self.cur
  259.         rtt = rtt + t
  260.         sft = rtt + rct
  261.  
  262.         pt, ptt, pct, pfn, pframe, pcur = rcur
  263.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  264.  
  265.         cc, ns, tt, ct, callers = self.timings[rfn]
  266.         if not ns:
  267.             ct = ct + sft
  268.             cc = cc + 1
  269.         if callers.has_key(pfn):
  270.             callers[pfn] = callers[pfn] + 1  # hack: gather more
  271.             # stats such as the amount of time added to ct courtesy
  272.             # of this specific call, and the contribution to cc
  273.             # courtesy of this call.
  274.         else:
  275.             callers[pfn] = 1
  276.         self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
  277.  
  278.         return 1
  279.  
  280.     # The next few function play with self.cmd. By carefully preloading
  281.     # our paralell stack, we can force the profiled result to include
  282.     # an arbitrary string as the name of the calling function.
  283.     # We use self.cmd as that string, and the resulting stats look
  284.     # very nice :-).
  285.  
  286.     def set_cmd(self, cmd):
  287.         if self.cur[-1]: return   # already set
  288.         self.cmd = cmd
  289.         self.simulate_call(cmd)
  290.  
  291.     class fake_code:
  292.         def __init__(self, filename, line, name):
  293.             self.co_filename = filename
  294.             self.co_line = line
  295.             self.co_name = name
  296.             self.co_code = '\0'  # anything but 127
  297.  
  298.         def __repr__(self):
  299.             return (self.co_filename, self.co_line, self.co_name)
  300.  
  301.     class fake_frame:
  302.         def __init__(self, code, prior):
  303.             self.f_code = code
  304.             self.f_back = prior
  305.             
  306.     def simulate_call(self, name):
  307.         code = self.fake_code('profile', 0, name)
  308.         if self.cur:
  309.             pframe = self.cur[-2]
  310.         else:
  311.             pframe = None
  312.         frame = self.fake_frame(code, pframe)
  313.         a = self.dispatch['call'](frame, 0)
  314.         return
  315.  
  316.     # collect stats from pending stack, including getting final
  317.     # timings for self.cmd frame.
  318.     
  319.     def simulate_cmd_complete(self):   
  320.         t = self.get_time() - self.t
  321.         while self.cur[-1]:
  322.             # We *can* cause assertion errors here if
  323.             # dispatch_trace_return checks for a frame match!
  324.             a = self.dispatch['return'](self.cur[-2], t)
  325.             t = 0
  326.         self.t = self.get_time() - t
  327.  
  328.     
  329.     def print_stats(self):
  330.         import pstats
  331.         pstats.Stats(self).strip_dirs().sort_stats(-1). \
  332.               print_stats()
  333.  
  334.     def dump_stats(self, file):
  335.         f = open(file, 'w')
  336.         self.create_stats()
  337.         marshal.dump(self.stats, f)
  338.         f.close()
  339.  
  340.     def create_stats(self):
  341.         self.simulate_cmd_complete()
  342.         self.snapshot_stats()
  343.  
  344.     def snapshot_stats(self):
  345.         self.stats = {}
  346.         for func in self.timings.keys():
  347.             cc, ns, tt, ct, callers = self.timings[func]
  348.             nor_func = self.func_normalize(func)
  349.             nor_callers = {}
  350.             nc = 0
  351.             for func_caller in callers.keys():
  352.                 nor_callers[self.func_normalize(func_caller)]=\
  353.                       callers[func_caller]
  354.                 nc = nc + callers[func_caller]
  355.             self.stats[nor_func] = cc, nc, tt, ct, nor_callers
  356.  
  357.  
  358.     # Override the following function if you can figure out
  359.     # a better name for the binary f_code entries.  I just normalize
  360.     # them sequentially in a dictionary.  It would be nice if we could
  361.     # *really* see the name of the underlying C code :-).  Sometimes
  362.     #  you can figure out what-is-what by looking at caller and callee
  363.     # lists (and knowing what your python code does).
  364.     
  365.     def func_normalize(self, func_name):
  366.         global func_norm_dict
  367.         global func_norm_counter
  368.         global func_sequence_num
  369.  
  370.         if func_norm_dict.has_key(func_name):
  371.             return func_norm_dict[func_name]
  372.         if type(func_name) == type(""):
  373.             long_name = string.split(func_name)
  374.             file_name = long_name[6][1:-2]
  375.             func = long_name[2]
  376.             lineno = long_name[8][:-1]
  377.             if '?' == func:   # Until I find out how to may 'em...
  378.                 file_name = 'python'
  379.                 func_norm_counter = func_norm_counter + 1
  380.                 func = pid_string + ".C." + `func_norm_counter`
  381.             result =  file_name ,  string.atoi(lineno) , func
  382.         else:
  383.             result = func_name
  384.         func_norm_dict[func_name] = result
  385.         return result
  386.  
  387.  
  388.     # The following two methods can be called by clients to use
  389.     # a profiler to profile a statement, given as a string.
  390.     
  391.     def run(self, cmd):
  392.         import __main__
  393.         dict = __main__.__dict__
  394.         self.runctx(cmd, dict, dict)
  395.         return self
  396.     
  397.     def runctx(self, cmd, globals, locals):
  398.         self.set_cmd(cmd)
  399.         sys.setprofile(self.trace_dispatch)
  400.         try:
  401.             exec(cmd, globals, locals)
  402.         finally:
  403.             sys.setprofile(None)
  404.  
  405.     # This method is more useful to profile a single function call.
  406.     def runcall(self, func, *args):
  407.         self.set_cmd(func.__name__)
  408.         sys.setprofile(self.trace_dispatch)
  409.         try:
  410.             apply(func, args)
  411.         finally:
  412.             sys.setprofile(None)
  413.         return self
  414.  
  415.  
  416.         #******************************************************************
  417.     # The following calculates the overhead for using a profiler.  The
  418.     # problem is that it takes a fair amount of time for the profiler
  419.     # to stop the stopwatch (from the time it recieves an event).
  420.     # Similarly, there is a delay from the time that the profiler
  421.     # re-starts the stopwatch before the user's code really gets to
  422.     # continue.  The following code tries to measure the difference on
  423.     # a per-event basis. The result can the be placed in the
  424.     # Profile.dispatch_event() routine for the given platform.  Note
  425.     # that this difference is only significant if there are a lot of
  426.     # events, and relatively little user code per event.  For example,
  427.     # code with small functions will typically benefit from having the
  428.     # profiler calibrated for the current platform.  This *could* be
  429.     # done on the fly during init() time, but it is not worth the
  430.     # effort.  Also note that if too large a value specified, then
  431.     # execution time on some functions will actually appear as a
  432.     # negative number.  It is *normal* for some functions (with very
  433.     # low call counts) to have such negative stats, even if the
  434.     # calibration figure is "correct." 
  435.     #
  436.     # One alternative to profile-time calibration adjustments (i.e.,
  437.     # adding in the magic little delta during each event) is to track
  438.     # more carefully the number of events (and cumulatively, the number
  439.     # of events during sub functions) that are seen.  If this were
  440.     # done, then the arithmetic could be done after the fact (i.e., at
  441.     # display time).  Currintly, we track only call/return events.
  442.     # These values can be deduced by examining the callees and callers
  443.     # vectors for each functions.  Hence we *can* almost correct the
  444.     # internal time figure at print time (note that we currently don't
  445.     # track exception event processing counts).  Unfortunately, there
  446.     # is currently no similar information for cumulative sub-function
  447.     # time.  It would not be hard to "get all this info" at profiler
  448.     # time.  Specifically, we would have to extend the tuples to keep
  449.     # counts of this in each frame, and then extend the defs of timing
  450.     # tuples to include the significant two figures. I'm a bit fearful
  451.     # that this additional feature will slow the heavily optimized
  452.     # event/time ratio (i.e., the profiler would run slower, fur a very
  453.     # low "value added" feature.) 
  454.     #
  455.     # Plugging in the calibration constant doesn't slow down the
  456.     # profiler very much, and the accuracy goes way up.
  457.     #**************************************************************
  458.     
  459.         def calibrate(self, m):
  460.         n = m
  461.         s = self.timer()
  462.         while n:
  463.             self.simple()
  464.             n = n - 1
  465.         f = self.timer()
  466.         my_simple = f[0]+f[1]-s[0]-s[1]
  467.         #print "Simple =", my_simple,
  468.  
  469.         n = m
  470.         s = self.timer()
  471.         while n:
  472.             self.instrumented()
  473.             n = n - 1
  474.         f = self.timer()
  475.         my_inst = f[0]+f[1]-s[0]-s[1]
  476.         # print "Instrumented =", my_inst
  477.         avg_cost = (my_inst - my_simple)/m
  478.         #print "Delta/call =", avg_cost, "(profiler fixup constant)"
  479.         return avg_cost
  480.  
  481.     # simulate a program with no profiler activity
  482.         def simple(self):      
  483.         a = 1
  484.         pass
  485.  
  486.     # simulate a program with call/return event processing
  487.         def instrumented(self):
  488.         a = 1
  489.         self.profiler_simulation(a, a, a)
  490.  
  491.     # simulate an event processing activity (from user's perspective)
  492.     def profiler_simulation(self, x, y, z):  
  493.         t = self.timer()
  494.         t = t[0] + t[1]
  495.         self.ut = t
  496.  
  497.  
  498.  
  499. #****************************************************************************
  500. # OldProfile class documentation
  501. #****************************************************************************
  502. #
  503. # The following derived profiler simulates the old style profile, providing
  504. # errant results on recursive functions. The reason for the usefulnes of this
  505. # profiler is that it runs faster (i.e., less overhead).  It still creates
  506. # all the caller stats, and is quite useful when there is *no* recursion
  507. # in the user's code.
  508. #
  509. # This code also shows how easy it is to create a modified profiler.
  510. #****************************************************************************
  511. class OldProfile(Profile):
  512.     def trace_dispatch_exception(self, frame, t):
  513.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  514.         if rcur and not rframe is frame:
  515.             return self.trace_dispatch_return(rframe, t)
  516.         return 0
  517.  
  518.     def trace_dispatch_call(self, frame, t):
  519.         fn = `frame.f_code`
  520.         
  521.         self.cur = (t, 0, 0, fn, frame, self.cur)
  522.         if self.timings.has_key(fn):
  523.             tt, ct, callers = self.timings[fn]
  524.             self.timings[fn] = tt, ct, callers
  525.         else:
  526.             self.timings[fn] = 0, 0, {}
  527.         return 1
  528.  
  529.     def trace_dispatch_return(self, frame, t):
  530.         rt, rtt, rct, rfn, frame, rcur = self.cur
  531.         rtt = rtt + t
  532.         sft = rtt + rct
  533.  
  534.         pt, ptt, pct, pfn, pframe, pcur = rcur
  535.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  536.  
  537.         tt, ct, callers = self.timings[rfn]
  538.         if callers.has_key(pfn):
  539.             callers[pfn] = callers[pfn] + 1
  540.         else:
  541.             callers[pfn] = 1
  542.         self.timings[rfn] = tt+rtt, ct + sft, callers
  543.  
  544.         return 1
  545.  
  546.  
  547.     def snapshot_stats(self):
  548.         self.stats = {}
  549.         for func in self.timings.keys():
  550.             tt, ct, callers = self.timings[func]
  551.             nor_func = self.func_normalize(func)
  552.             nor_callers = {}
  553.             nc = 0
  554.             for func_caller in callers.keys():
  555.                 nor_callers[self.func_normalize(func_caller)]=\
  556.                       callers[func_caller]
  557.                 nc = nc + callers[func_caller]
  558.             self.stats[nor_func] = nc, nc, tt, ct, nor_callers
  559.  
  560.         
  561.  
  562. #****************************************************************************
  563. # HotProfile class documentation
  564. #****************************************************************************
  565. #
  566. # This profiler is the fastest derived profile example.  It does not
  567. # calculate caller-callee relationships, and does not calculate cumulative
  568. # time under a function.  It only calculates time spent in a function, so
  569. # it runs very quickly (re: very low overhead)
  570. #****************************************************************************
  571. class HotProfile(Profile):
  572.     def trace_dispatch_exception(self, frame, t):
  573.         rt, rtt, rfn, rframe, rcur = self.cur
  574.         if rcur and not rframe is frame:
  575.             return self.trace_dispatch_return(rframe, t)
  576.         return 0
  577.  
  578.     def trace_dispatch_call(self, frame, t):
  579.         self.cur = (t, 0, frame, self.cur)
  580.         return 1
  581.  
  582.     def trace_dispatch_return(self, frame, t):
  583.         rt, rtt, frame, rcur = self.cur
  584.  
  585.         rfn = `frame.f_code`
  586.  
  587.         pt, ptt, pframe, pcur = rcur
  588.         self.cur = pt, ptt+rt, pframe, pcur
  589.  
  590.         if self.timings.has_key(rfn):
  591.             nc, tt = self.timings[rfn]
  592.             self.timings[rfn] = nc + 1, rt + rtt + tt
  593.         else:
  594.             self.timings[rfn] =      1, rt + rtt
  595.  
  596.         return 1
  597.  
  598.  
  599.     def snapshot_stats(self):
  600.         self.stats = {}
  601.         for func in self.timings.keys():
  602.             nc, tt = self.timings[func]
  603.             nor_func = self.func_normalize(func)
  604.             self.stats[nor_func] = nc, nc, tt, 0, {}
  605.  
  606.         
  607.  
  608. #****************************************************************************
  609. def Stats(*args):
  610.     print 'Report generating functions are in the "pstats" module\a'
  611.