home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / profile.py < prev    next >
Text File  |  1997-10-08  |  21KB  |  651 lines

  1. #! /usr/bin/env python
  2. #
  3. # Class for profiling python code. rev 1.0  6/2/94
  4. #
  5. # Based on prior profile module by Sjoerd Mullender...
  6. #   which was hacked somewhat by: Guido van Rossum
  7. #
  8. # See profile.doc for more information
  9.  
  10.  
  11. # Copyright 1994, by InfoSeek Corporation, all rights reserved.
  12. # Written by James Roskind
  13. # Permission to use, copy, modify, and distribute this Python software
  14. # and its associated documentation for any purpose (subject to the
  15. # restriction in the following sentence) without fee is hereby granted,
  16. # provided that the above copyright notice appears in all copies, and
  17. # that both that copyright notice and this permission notice appear in
  18. # supporting documentation, and that the name of InfoSeek not be used in
  19. # advertising or publicity pertaining to distribution of the software
  20. # without specific, written prior permission.  This permission is
  21. # explicitly restricted to the copying and modification of the software
  22. # to remain in Python, compiled Python, or other languages (such as C)
  23. # wherein the modified or derived code is exclusively imported into a
  24. # Python module.
  25. # INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
  26. # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  27. # FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
  28. # SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
  29. # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  30. # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  31. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  32.  
  33.  
  34.  
  35. import sys
  36. import os
  37. import time
  38. import string
  39. import marshal
  40.  
  41.  
  42. # Global variables
  43. func_norm_dict = {}
  44. func_norm_counter = 0
  45. if hasattr(os, 'getpid'):
  46.     pid_string = `os.getpid()`
  47. else:
  48.     pid_string = ''
  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, timer=None):
  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 timer:
  150.             if hasattr(os, 'times'):
  151.                 self.timer = os.times
  152.                 self.dispatcher = self.trace_dispatch
  153.             elif os.name == 'mac':
  154.                 import MacOS
  155.                 self.timer = MacOS.GetTicks
  156.                 self.dispatcher = self.trace_dispatch_mac
  157.                 self.get_time = self.get_time_mac
  158.             else:
  159.                 self.timer = time.time
  160.                 self.dispatcher = self.trace_dispatch_i
  161.         else:
  162.             self.timer = timer
  163.             t = self.timer() # test out timer function
  164.             try:
  165.                 if len(t) == 2:
  166.                     self.dispatcher = self.trace_dispatch
  167.                 else:
  168.                     self.dispatcher = self.trace_dispatch_l
  169.             except TypeError:
  170.                 self.dispatcher = self.trace_dispatch_i
  171.         self.t = self.get_time()
  172.         self.simulate_call('profiler')
  173.  
  174.  
  175.     def get_time(self): # slow simulation of method to acquire time
  176.         t = self.timer()
  177.         if type(t) == type(()) or type(t) == type([]):
  178.             t = reduce(lambda x,y: x+y, t, 0)
  179.         return t
  180.         
  181.     def get_time_mac(self):
  182.         return self.timer()/60.0
  183.  
  184.     # Heavily optimized dispatch routine for os.times() timer
  185.  
  186.     def trace_dispatch(self, frame, event, arg):
  187.         t = self.timer()
  188.         t = t[0] + t[1] - self.t        # No Calibration constant
  189.         # t = t[0] + t[1] - self.t - .00053 # Calibration constant
  190.  
  191.         if self.dispatch[event](frame,t):
  192.             t = self.timer()
  193.             self.t = t[0] + t[1]
  194.         else:
  195.             r = self.timer()
  196.             self.t = r[0] + r[1] - t # put back unrecorded delta
  197.         return
  198.  
  199.  
  200.  
  201.     # Dispatch routine for best timer program (return = scalar integer)
  202.  
  203.     def trace_dispatch_i(self, frame, event, arg):
  204.         t = self.timer() - self.t # - 1 # Integer calibration constant
  205.         if self.dispatch[event](frame,t):
  206.             self.t = self.timer()
  207.         else:
  208.             self.t = self.timer() - t  # put back unrecorded delta
  209.         return
  210.     
  211.     # Dispatch routine for macintosh (timer returns time in ticks of 1/60th second)
  212.  
  213.     def trace_dispatch_mac(self, frame, event, arg):
  214.         t = self.timer()/60.0 - self.t # - 1 # Integer calibration constant
  215.         if self.dispatch[event](frame,t):
  216.             self.t = self.timer()/60.0
  217.         else:
  218.             self.t = self.timer()/60.0 - t  # put back unrecorded delta
  219.         return
  220.  
  221.  
  222.     # SLOW generic dispatch rountine for timer returning lists of numbers
  223.  
  224.     def trace_dispatch_l(self, frame, event, arg):
  225.         t = self.get_time() - self.t
  226.  
  227.         if self.dispatch[event](frame,t):
  228.             self.t = self.get_time()
  229.         else:
  230.             self.t = self.get_time()-t # put back unrecorded delta
  231.         return
  232.  
  233.  
  234.     def trace_dispatch_exception(self, frame, t):
  235.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  236.         if (not rframe is frame) and rcur:
  237.             return self.trace_dispatch_return(rframe, t)
  238.         return 0
  239.  
  240.  
  241.     def trace_dispatch_call(self, frame, t):
  242.         fn = `frame.f_code` 
  243.  
  244.         # The following should be about the best approach, but
  245.         # we would need a function that maps from id() back to
  246.         # the actual code object.  
  247.         #     fn = id(frame.f_code)
  248.         # Note we would really use our own function, which would
  249.         # return the code address, *and* bump the ref count.  We
  250.         # would then fix up the normalize function to do the
  251.         # actualy repr(fn) call.
  252.  
  253.         # The following is an interesting alternative
  254.         # It doesn't do as good a job, and it doesn't run as
  255.         # fast 'cause repr() is written in C, and this is Python.
  256.         #fcode = frame.f_code
  257.         #code = fcode.co_code
  258.         #if ord(code[0]) == 127: #  == SET_LINENO
  259.         #    # see "opcode.h" in the Python source
  260.         #    fn = (fcode.co_filename, ord(code[1]) | \
  261.         #          ord(code[2]) << 8, fcode.co_name)
  262.         #else:
  263.         #    fn = (fcode.co_filename, 0, fcode.co_name)
  264.  
  265.         self.cur = (t, 0, 0, fn, frame, self.cur)
  266.         if self.timings.has_key(fn):
  267.             cc, ns, tt, ct, callers = self.timings[fn]
  268.             self.timings[fn] = cc, ns + 1, tt, ct, callers
  269.         else:
  270.             self.timings[fn] = 0, 0, 0, 0, {}
  271.         return 1
  272.  
  273.     def trace_dispatch_return(self, frame, t):
  274.         # if not frame is self.cur[-2]: raise "Bad return", self.cur[3]
  275.  
  276.         # Prefix "r" means part of the Returning or exiting frame
  277.         # Prefix "p" means part of the Previous or older frame
  278.  
  279.         rt, rtt, rct, rfn, frame, rcur = self.cur
  280.         rtt = rtt + t
  281.         sft = rtt + rct
  282.  
  283.         pt, ptt, pct, pfn, pframe, pcur = rcur
  284.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  285.  
  286.         cc, ns, tt, ct, callers = self.timings[rfn]
  287.         if not ns:
  288.             ct = ct + sft
  289.             cc = cc + 1
  290.         if callers.has_key(pfn):
  291.             callers[pfn] = callers[pfn] + 1  # hack: gather more
  292.             # stats such as the amount of time added to ct courtesy
  293.             # of this specific call, and the contribution to cc
  294.             # courtesy of this call.
  295.         else:
  296.             callers[pfn] = 1
  297.         self.timings[rfn] = cc, ns - 1, tt+rtt, ct, callers
  298.  
  299.         return 1
  300.  
  301.     # The next few function play with self.cmd. By carefully preloading
  302.     # our paralell stack, we can force the profiled result to include
  303.     # an arbitrary string as the name of the calling function.
  304.     # We use self.cmd as that string, and the resulting stats look
  305.     # very nice :-).
  306.  
  307.     def set_cmd(self, cmd):
  308.         if self.cur[-1]: return   # already set
  309.         self.cmd = cmd
  310.         self.simulate_call(cmd)
  311.  
  312.     class fake_code:
  313.         def __init__(self, filename, line, name):
  314.             self.co_filename = filename
  315.             self.co_line = line
  316.             self.co_name = name
  317.             self.co_code = '\0'  # anything but 127
  318.  
  319.         def __repr__(self):
  320.             return (self.co_filename, self.co_line, self.co_name)
  321.  
  322.     class fake_frame:
  323.         def __init__(self, code, prior):
  324.             self.f_code = code
  325.             self.f_back = prior
  326.             
  327.     def simulate_call(self, name):
  328.         code = self.fake_code('profile', 0, name)
  329.         if self.cur:
  330.             pframe = self.cur[-2]
  331.         else:
  332.             pframe = None
  333.         frame = self.fake_frame(code, pframe)
  334.         a = self.dispatch['call'](frame, 0)
  335.         return
  336.  
  337.     # collect stats from pending stack, including getting final
  338.     # timings for self.cmd frame.
  339.     
  340.     def simulate_cmd_complete(self):   
  341.         t = self.get_time() - self.t
  342.         while self.cur[-1]:
  343.             # We *can* cause assertion errors here if
  344.             # dispatch_trace_return checks for a frame match!
  345.             a = self.dispatch['return'](self.cur[-2], t)
  346.             t = 0
  347.         self.t = self.get_time() - t
  348.  
  349.     
  350.     def print_stats(self):
  351.         import pstats
  352.         pstats.Stats(self).strip_dirs().sort_stats(-1). \
  353.               print_stats()
  354.  
  355.     def dump_stats(self, file):
  356.         f = open(file, 'wb')
  357.         self.create_stats()
  358.         marshal.dump(self.stats, f)
  359.         f.close()
  360.  
  361.     def create_stats(self):
  362.         self.simulate_cmd_complete()
  363.         self.snapshot_stats()
  364.  
  365.     def snapshot_stats(self):
  366.         self.stats = {}
  367.         for func in self.timings.keys():
  368.             cc, ns, tt, ct, callers = self.timings[func]
  369.             nor_func = self.func_normalize(func)
  370.             nor_callers = {}
  371.             nc = 0
  372.             for func_caller in callers.keys():
  373.                 nor_callers[self.func_normalize(func_caller)]=\
  374.                       callers[func_caller]
  375.                 nc = nc + callers[func_caller]
  376.             self.stats[nor_func] = cc, nc, tt, ct, nor_callers
  377.  
  378.  
  379.     # Override the following function if you can figure out
  380.     # a better name for the binary f_code entries.  I just normalize
  381.     # them sequentially in a dictionary.  It would be nice if we could
  382.     # *really* see the name of the underlying C code :-).  Sometimes
  383.     #  you can figure out what-is-what by looking at caller and callee
  384.     # lists (and knowing what your python code does).
  385.     
  386.     def func_normalize(self, func_name):
  387.         global func_norm_dict
  388.         global func_norm_counter
  389.         global func_sequence_num
  390.  
  391.         if func_norm_dict.has_key(func_name):
  392.             return func_norm_dict[func_name]
  393.         if type(func_name) == type(""):
  394.             long_name = string.split(func_name)
  395.             file_name = long_name[-3][1:-2]
  396.             func = long_name[2]
  397.             lineno = long_name[-1][:-1]
  398.             if '?' == func:   # Until I find out how to may 'em...
  399.                 file_name = 'python'
  400.                 func_norm_counter = func_norm_counter + 1
  401.                 func = pid_string + ".C." + `func_norm_counter`
  402.             result =  file_name ,  string.atoi(lineno) , func
  403.         else:
  404.             result = func_name
  405.         func_norm_dict[func_name] = result
  406.         return result
  407.  
  408.  
  409.     # The following two methods can be called by clients to use
  410.     # a profiler to profile a statement, given as a string.
  411.     
  412.     def run(self, cmd):
  413.         import __main__
  414.         dict = __main__.__dict__
  415.         return self.runctx(cmd, dict, dict)
  416.     
  417.     def runctx(self, cmd, globals, locals):
  418.         self.set_cmd(cmd)
  419.         sys.setprofile(self.dispatcher)
  420.         try:
  421.             exec cmd in globals, locals
  422.         finally:
  423.             sys.setprofile(None)
  424.         return self
  425.  
  426.     # This method is more useful to profile a single function call.
  427.     def runcall(self, func, *args):
  428.         self.set_cmd(`func`)
  429.         sys.setprofile(self.dispatcher)
  430.         try:
  431.             return apply(func, args)
  432.         finally:
  433.             sys.setprofile(None)
  434.  
  435.  
  436.         #******************************************************************
  437.     # The following calculates the overhead for using a profiler.  The
  438.     # problem is that it takes a fair amount of time for the profiler
  439.     # to stop the stopwatch (from the time it recieves an event).
  440.     # Similarly, there is a delay from the time that the profiler
  441.     # re-starts the stopwatch before the user's code really gets to
  442.     # continue.  The following code tries to measure the difference on
  443.     # a per-event basis. The result can the be placed in the
  444.     # Profile.dispatch_event() routine for the given platform.  Note
  445.     # that this difference is only significant if there are a lot of
  446.     # events, and relatively little user code per event.  For example,
  447.     # code with small functions will typically benefit from having the
  448.     # profiler calibrated for the current platform.  This *could* be
  449.     # done on the fly during init() time, but it is not worth the
  450.     # effort.  Also note that if too large a value specified, then
  451.     # execution time on some functions will actually appear as a
  452.     # negative number.  It is *normal* for some functions (with very
  453.     # low call counts) to have such negative stats, even if the
  454.     # calibration figure is "correct." 
  455.     #
  456.     # One alternative to profile-time calibration adjustments (i.e.,
  457.     # adding in the magic little delta during each event) is to track
  458.     # more carefully the number of events (and cumulatively, the number
  459.     # of events during sub functions) that are seen.  If this were
  460.     # done, then the arithmetic could be done after the fact (i.e., at
  461.     # display time).  Currintly, we track only call/return events.
  462.     # These values can be deduced by examining the callees and callers
  463.     # vectors for each functions.  Hence we *can* almost correct the
  464.     # internal time figure at print time (note that we currently don't
  465.     # track exception event processing counts).  Unfortunately, there
  466.     # is currently no similar information for cumulative sub-function
  467.     # time.  It would not be hard to "get all this info" at profiler
  468.     # time.  Specifically, we would have to extend the tuples to keep
  469.     # counts of this in each frame, and then extend the defs of timing
  470.     # tuples to include the significant two figures. I'm a bit fearful
  471.     # that this additional feature will slow the heavily optimized
  472.     # event/time ratio (i.e., the profiler would run slower, fur a very
  473.     # low "value added" feature.) 
  474.     #
  475.     # Plugging in the calibration constant doesn't slow down the
  476.     # profiler very much, and the accuracy goes way up.
  477.     #**************************************************************
  478.     
  479.         def calibrate(self, m):
  480.         n = m
  481.         s = self.timer()
  482.         while n:
  483.             self.simple()
  484.             n = n - 1
  485.         f = self.timer()
  486.         my_simple = f[0]+f[1]-s[0]-s[1]
  487.         #print "Simple =", my_simple,
  488.  
  489.         n = m
  490.         s = self.timer()
  491.         while n:
  492.             self.instrumented()
  493.             n = n - 1
  494.         f = self.timer()
  495.         my_inst = f[0]+f[1]-s[0]-s[1]
  496.         # print "Instrumented =", my_inst
  497.         avg_cost = (my_inst - my_simple)/m
  498.         #print "Delta/call =", avg_cost, "(profiler fixup constant)"
  499.         return avg_cost
  500.  
  501.     # simulate a program with no profiler activity
  502.         def simple(self):      
  503.         a = 1
  504.         pass
  505.  
  506.     # simulate a program with call/return event processing
  507.         def instrumented(self):
  508.         a = 1
  509.         self.profiler_simulation(a, a, a)
  510.  
  511.     # simulate an event processing activity (from user's perspective)
  512.     def profiler_simulation(self, x, y, z):  
  513.         t = self.timer()
  514.         t = t[0] + t[1]
  515.         self.ut = t
  516.  
  517.  
  518.  
  519. #****************************************************************************
  520. # OldProfile class documentation
  521. #****************************************************************************
  522. #
  523. # The following derived profiler simulates the old style profile, providing
  524. # errant results on recursive functions. The reason for the usefulnes of this
  525. # profiler is that it runs faster (i.e., less overhead).  It still creates
  526. # all the caller stats, and is quite useful when there is *no* recursion
  527. # in the user's code.
  528. #
  529. # This code also shows how easy it is to create a modified profiler.
  530. #****************************************************************************
  531. class OldProfile(Profile):
  532.     def trace_dispatch_exception(self, frame, t):
  533.         rt, rtt, rct, rfn, rframe, rcur = self.cur
  534.         if rcur and not rframe is frame:
  535.             return self.trace_dispatch_return(rframe, t)
  536.         return 0
  537.  
  538.     def trace_dispatch_call(self, frame, t):
  539.         fn = `frame.f_code`
  540.         
  541.         self.cur = (t, 0, 0, fn, frame, self.cur)
  542.         if self.timings.has_key(fn):
  543.             tt, ct, callers = self.timings[fn]
  544.             self.timings[fn] = tt, ct, callers
  545.         else:
  546.             self.timings[fn] = 0, 0, {}
  547.         return 1
  548.  
  549.     def trace_dispatch_return(self, frame, t):
  550.         rt, rtt, rct, rfn, frame, rcur = self.cur
  551.         rtt = rtt + t
  552.         sft = rtt + rct
  553.  
  554.         pt, ptt, pct, pfn, pframe, pcur = rcur
  555.         self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  556.  
  557.         tt, ct, callers = self.timings[rfn]
  558.         if callers.has_key(pfn):
  559.             callers[pfn] = callers[pfn] + 1
  560.         else:
  561.             callers[pfn] = 1
  562.         self.timings[rfn] = tt+rtt, ct + sft, callers
  563.  
  564.         return 1
  565.  
  566.  
  567.     def snapshot_stats(self):
  568.         self.stats = {}
  569.         for func in self.timings.keys():
  570.             tt, ct, callers = self.timings[func]
  571.             nor_func = self.func_normalize(func)
  572.             nor_callers = {}
  573.             nc = 0
  574.             for func_caller in callers.keys():
  575.                 nor_callers[self.func_normalize(func_caller)]=\
  576.                       callers[func_caller]
  577.                 nc = nc + callers[func_caller]
  578.             self.stats[nor_func] = nc, nc, tt, ct, nor_callers
  579.  
  580.         
  581.  
  582. #****************************************************************************
  583. # HotProfile class documentation
  584. #****************************************************************************
  585. #
  586. # This profiler is the fastest derived profile example.  It does not
  587. # calculate caller-callee relationships, and does not calculate cumulative
  588. # time under a function.  It only calculates time spent in a function, so
  589. # it runs very quickly (re: very low overhead)
  590. #****************************************************************************
  591. class HotProfile(Profile):
  592.     def trace_dispatch_exception(self, frame, t):
  593.         rt, rtt, rfn, rframe, rcur = self.cur
  594.         if rcur and not rframe is frame:
  595.             return self.trace_dispatch_return(rframe, t)
  596.         return 0
  597.  
  598.     def trace_dispatch_call(self, frame, t):
  599.         self.cur = (t, 0, frame, self.cur)
  600.         return 1
  601.  
  602.     def trace_dispatch_return(self, frame, t):
  603.         rt, rtt, frame, rcur = self.cur
  604.  
  605.         rfn = `frame.f_code`
  606.  
  607.         pt, ptt, pframe, pcur = rcur
  608.         self.cur = pt, ptt+rt, pframe, pcur
  609.  
  610.         if self.timings.has_key(rfn):
  611.             nc, tt = self.timings[rfn]
  612.             self.timings[rfn] = nc + 1, rt + rtt + tt
  613.         else:
  614.             self.timings[rfn] =      1, rt + rtt
  615.  
  616.         return 1
  617.  
  618.  
  619.     def snapshot_stats(self):
  620.         self.stats = {}
  621.         for func in self.timings.keys():
  622.             nc, tt = self.timings[func]
  623.             nor_func = self.func_normalize(func)
  624.             self.stats[nor_func] = nc, nc, tt, 0, {}
  625.  
  626.         
  627.  
  628. #****************************************************************************
  629. def Stats(*args):
  630.     print 'Report generating functions are in the "pstats" module\a'
  631.  
  632.  
  633. # When invoked as main program, invoke the profiler on a script
  634. if __name__ == '__main__':
  635.     import sys
  636.     import os
  637.     if not sys.argv[1:]:
  638.         print "usage: profile.py scriptfile [arg] ..."
  639.         sys.exit(2)
  640.  
  641.     filename = sys.argv[1]    # Get script filename
  642.  
  643.     del sys.argv[0]        # Hide "profile.py" from argument list
  644.  
  645.     # Insert script directory in front of module search path
  646.     sys.path.insert(0, os.path.dirname(filename))
  647.  
  648.     run('execfile(' + `filename` + ')')
  649.