home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_676 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  12.5 KB  |  453 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import sys
  5. import os
  6. import time
  7. import marshal
  8. from optparse import OptionParser
  9. __all__ = [
  10.     'run',
  11.     'runctx',
  12.     'help',
  13.     'Profile']
  14.  
  15. def run(statement, filename = None, sort = -1):
  16.     prof = Profile()
  17.     
  18.     try:
  19.         prof = prof.run(statement)
  20.     except SystemExit:
  21.         pass
  22.  
  23.     if filename is not None:
  24.         prof.dump_stats(filename)
  25.     else:
  26.         return prof.print_stats(sort)
  27.     return filename is not None
  28.  
  29.  
  30. def runctx(statement, globals, locals, filename = None):
  31.     prof = Profile()
  32.     
  33.     try:
  34.         prof = prof.runctx(statement, globals, locals)
  35.     except SystemExit:
  36.         pass
  37.  
  38.     if filename is not None:
  39.         prof.dump_stats(filename)
  40.     else:
  41.         return prof.print_stats()
  42.     return filename is not None
  43.  
  44.  
  45. def help():
  46.     print 'Documentation for the profile module can be found '
  47.     print "in the Python Library Reference, section 'The Python Profiler'."
  48.  
  49. if os.name == 'mac':
  50.     import MacOS
  51.     
  52.     def _get_time_mac(timer = MacOS.GetTicks):
  53.         return timer() / 60
  54.  
  55.  
  56. if hasattr(os, 'times'):
  57.     
  58.     def _get_time_times(timer = os.times):
  59.         t = timer()
  60.         return t[0] + t[1]
  61.  
  62.  
  63. _has_res = 0
  64.  
  65. try:
  66.     import resource
  67.     
  68.     resgetrusage = lambda : resource.getrusage(resource.RUSAGE_SELF)
  69.     
  70.     def _get_time_resource(timer = resgetrusage):
  71.         t = timer()
  72.         return t[0] + t[1]
  73.  
  74.     _has_res = 1
  75. except ImportError:
  76.     pass
  77.  
  78.  
  79. class Profile:
  80.     bias = 0
  81.     
  82.     def __init__(self, timer = None, bias = None):
  83.         self.timings = { }
  84.         self.cur = None
  85.         self.cmd = ''
  86.         self.c_func_name = ''
  87.         if bias is None:
  88.             bias = self.bias
  89.         
  90.         self.bias = bias
  91.         if not timer:
  92.             if _has_res:
  93.                 self.timer = resgetrusage
  94.                 self.dispatcher = self.trace_dispatch
  95.                 self.get_time = _get_time_resource
  96.             elif os.name == 'mac':
  97.                 self.timer = MacOS.GetTicks
  98.                 self.dispatcher = self.trace_dispatch_mac
  99.                 self.get_time = _get_time_mac
  100.             elif hasattr(time, 'clock'):
  101.                 self.timer = self.get_time = time.clock
  102.                 self.dispatcher = self.trace_dispatch_i
  103.             elif hasattr(os, 'times'):
  104.                 self.timer = os.times
  105.                 self.dispatcher = self.trace_dispatch
  106.                 self.get_time = _get_time_times
  107.             else:
  108.                 self.timer = self.get_time = time.time
  109.                 self.dispatcher = self.trace_dispatch_i
  110.         else:
  111.             self.timer = timer
  112.             t = self.timer()
  113.             
  114.             try:
  115.                 length = len(t)
  116.             except TypeError:
  117.                 self.get_time = timer
  118.                 self.dispatcher = self.trace_dispatch_i
  119.  
  120.             if length == 2:
  121.                 self.dispatcher = self.trace_dispatch
  122.             else:
  123.                 self.dispatcher = self.trace_dispatch_l
  124.             
  125.             def get_time_timer(timer = timer, sum = sum):
  126.                 return sum(timer())
  127.  
  128.             self.get_time = get_time_timer
  129.         self.t = self.get_time()
  130.         self.simulate_call('profiler')
  131.  
  132.     
  133.     def trace_dispatch(self, frame, event, arg):
  134.         timer = self.timer
  135.         t = timer()
  136.         t = t[0] + t[1] - self.t - self.bias
  137.         if event == 'c_call':
  138.             self.c_func_name = arg.__name__
  139.         
  140.         if self.dispatch[event](self, frame, t):
  141.             t = timer()
  142.             self.t = t[0] + t[1]
  143.         else:
  144.             r = timer()
  145.             self.t = r[0] + r[1] - t
  146.  
  147.     
  148.     def trace_dispatch_i(self, frame, event, arg):
  149.         timer = self.timer
  150.         t = timer() - self.t - self.bias
  151.         if event == 'c_call':
  152.             self.c_func_name = arg.__name__
  153.         
  154.         if self.dispatch[event](self, frame, t):
  155.             self.t = timer()
  156.         else:
  157.             self.t = timer() - t
  158.  
  159.     
  160.     def trace_dispatch_mac(self, frame, event, arg):
  161.         timer = self.timer
  162.         t = timer() / 60 - self.t - self.bias
  163.         if event == 'c_call':
  164.             self.c_func_name = arg.__name__
  165.         
  166.         if self.dispatch[event](self, frame, t):
  167.             self.t = timer() / 60
  168.         else:
  169.             self.t = timer() / 60 - t
  170.  
  171.     
  172.     def trace_dispatch_l(self, frame, event, arg):
  173.         get_time = self.get_time
  174.         t = get_time() - self.t - self.bias
  175.         if event == 'c_call':
  176.             self.c_func_name = arg.__name__
  177.         
  178.         if self.dispatch[event](self, frame, t):
  179.             self.t = get_time()
  180.         else:
  181.             self.t = get_time() - t
  182.  
  183.     
  184.     def trace_dispatch_exception(self, frame, t):
  185.         (rpt, rit, ret, rfn, rframe, rcur) = self.cur
  186.         if rframe is not frame and rcur:
  187.             return self.trace_dispatch_return(rframe, t)
  188.         self.cur = (rpt, rit + t, ret, rfn, rframe, rcur)
  189.         return 1
  190.  
  191.     
  192.     def trace_dispatch_call(self, frame, t):
  193.         if self.cur and frame.f_back is not self.cur[-2]:
  194.             (rpt, rit, ret, rfn, rframe, rcur) = self.cur
  195.             if not isinstance(rframe, Profile.fake_frame):
  196.                 self.trace_dispatch_return(rframe, 0)
  197.             
  198.         
  199.         fcode = frame.f_code
  200.         fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name)
  201.         self.cur = (t, 0, 0, fn, frame, self.cur)
  202.         timings = self.timings
  203.         if fn in timings:
  204.             (cc, ns, tt, ct, callers) = timings[fn]
  205.             timings[fn] = (cc, ns + 1, tt, ct, callers)
  206.         else:
  207.             timings[fn] = (0, 0, 0, 0, { })
  208.         return 1
  209.  
  210.     
  211.     def trace_dispatch_c_call(self, frame, t):
  212.         fn = ('', 0, self.c_func_name)
  213.         self.cur = (t, 0, 0, fn, frame, self.cur)
  214.         timings = self.timings
  215.         if fn in timings:
  216.             (cc, ns, tt, ct, callers) = timings[fn]
  217.             timings[fn] = (cc, ns + 1, tt, ct, callers)
  218.         else:
  219.             timings[fn] = (0, 0, 0, 0, { })
  220.         return 1
  221.  
  222.     
  223.     def trace_dispatch_return(self, frame, t):
  224.         if frame is not self.cur[-2]:
  225.             self.trace_dispatch_return(self.cur[-2], 0)
  226.         
  227.         (rpt, rit, ret, rfn, frame, rcur) = self.cur
  228.         rit = rit + t
  229.         frame_total = rit + ret
  230.         (ppt, pit, pet, pfn, pframe, pcur) = rcur
  231.         self.cur = (ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur)
  232.         timings = self.timings
  233.         (cc, ns, tt, ct, callers) = timings[rfn]
  234.         if not ns:
  235.             ct = ct + frame_total
  236.             cc = cc + 1
  237.         
  238.         if pfn in callers:
  239.             callers[pfn] = callers[pfn] + 1
  240.         else:
  241.             callers[pfn] = 1
  242.         timings[rfn] = (cc, ns - 1, tt + rit, ct, callers)
  243.         return 1
  244.  
  245.     dispatch = {
  246.         'call': trace_dispatch_call,
  247.         'exception': trace_dispatch_exception,
  248.         'return': trace_dispatch_return,
  249.         'c_call': trace_dispatch_c_call,
  250.         'c_exception': trace_dispatch_return,
  251.         'c_return': trace_dispatch_return }
  252.     
  253.     def set_cmd(self, cmd):
  254.         if self.cur[-1]:
  255.             return None
  256.         self.cmd = cmd
  257.         self.simulate_call(cmd)
  258.  
  259.     
  260.     class fake_code:
  261.         
  262.         def __init__(self, filename, line, name):
  263.             self.co_filename = filename
  264.             self.co_line = line
  265.             self.co_name = name
  266.             self.co_firstlineno = 0
  267.  
  268.         
  269.         def __repr__(self):
  270.             return repr((self.co_filename, self.co_line, self.co_name))
  271.  
  272.  
  273.     
  274.     class fake_frame:
  275.         
  276.         def __init__(self, code, prior):
  277.             self.f_code = code
  278.             self.f_back = prior
  279.  
  280.  
  281.     
  282.     def simulate_call(self, name):
  283.         code = self.fake_code('profile', 0, name)
  284.         if self.cur:
  285.             pframe = self.cur[-2]
  286.         else:
  287.             pframe = None
  288.         frame = self.fake_frame(code, pframe)
  289.         self.dispatch['call'](self, frame, 0)
  290.  
  291.     
  292.     def simulate_cmd_complete(self):
  293.         get_time = self.get_time
  294.         t = get_time() - self.t
  295.         while self.cur[-1]:
  296.             self.dispatch['return'](self, self.cur[-2], t)
  297.             t = 0
  298.         self.t = get_time() - t
  299.  
  300.     
  301.     def print_stats(self, sort = -1):
  302.         import pstats
  303.         pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
  304.  
  305.     
  306.     def dump_stats(self, file):
  307.         f = open(file, 'wb')
  308.         self.create_stats()
  309.         marshal.dump(self.stats, f)
  310.         f.close()
  311.  
  312.     
  313.     def create_stats(self):
  314.         self.simulate_cmd_complete()
  315.         self.snapshot_stats()
  316.  
  317.     
  318.     def snapshot_stats(self):
  319.         self.stats = { }
  320.         for cc, ns, tt, ct, callers in self.timings.iteritems():
  321.             callers = callers.copy()
  322.             nc = 0
  323.             for callcnt in callers.itervalues():
  324.                 nc += callcnt
  325.             
  326.             self.stats[func] = (cc, nc, tt, ct, callers)
  327.         
  328.  
  329.     
  330.     def run(self, cmd):
  331.         import __main__
  332.         dict = __main__.__dict__
  333.         return self.runctx(cmd, dict, dict)
  334.  
  335.     
  336.     def runctx(self, cmd, globals, locals):
  337.         self.set_cmd(cmd)
  338.         sys.setprofile(self.dispatcher)
  339.         
  340.         try:
  341.             exec cmd in globals, locals
  342.         finally:
  343.             sys.setprofile(None)
  344.  
  345.         return self
  346.  
  347.     
  348.     def runcall(self, func, *args, **kw):
  349.         self.set_cmd(repr(func))
  350.         sys.setprofile(self.dispatcher)
  351.         
  352.         try:
  353.             return func(*args, **kw)
  354.         finally:
  355.             sys.setprofile(None)
  356.  
  357.  
  358.     
  359.     def calibrate(self, m, verbose = 0):
  360.         if self.__class__ is not Profile:
  361.             raise TypeError('Subclasses must override .calibrate().')
  362.         self.__class__ is not Profile
  363.         saved_bias = self.bias
  364.         self.bias = 0
  365.         
  366.         try:
  367.             return self._calibrate_inner(m, verbose)
  368.         finally:
  369.             self.bias = saved_bias
  370.  
  371.  
  372.     
  373.     def _calibrate_inner(self, m, verbose):
  374.         get_time = self.get_time
  375.         
  376.         def f1(n):
  377.             for i in range(n):
  378.                 x = 1
  379.             
  380.  
  381.         
  382.         def f(m, f1 = f1):
  383.             for i in range(m):
  384.                 f1(100)
  385.             
  386.  
  387.         f(m)
  388.         t0 = get_time()
  389.         f(m)
  390.         t1 = get_time()
  391.         elapsed_noprofile = t1 - t0
  392.         if verbose:
  393.             print 'elapsed time without profiling =', elapsed_noprofile
  394.         
  395.         p = Profile()
  396.         t0 = get_time()
  397.         p.runctx('f(m)', globals(), locals())
  398.         t1 = get_time()
  399.         elapsed_profile = t1 - t0
  400.         if verbose:
  401.             print 'elapsed time with profiling =', elapsed_profile
  402.         
  403.         total_calls = 0
  404.         reported_time = 0
  405.         for filename, line, funcname in p.timings.items():
  406.             (cc, ns, tt, ct, callers) = None
  407.             if funcname in ('f', 'f1'):
  408.                 total_calls += cc
  409.                 reported_time += tt
  410.                 continue
  411.         
  412.         if verbose:
  413.             print "'CPU seconds' profiler reported =", reported_time
  414.             print 'total # calls =', total_calls
  415.         
  416.         if total_calls != m + 1:
  417.             raise ValueError('internal error: total calls = %d' % total_calls)
  418.         total_calls != m + 1
  419.         mean = (reported_time - elapsed_noprofile) / 2 / total_calls
  420.         if verbose:
  421.             print 'mean stopwatch overhead per profile event =', mean
  422.         
  423.         return mean
  424.  
  425.  
  426.  
  427. def Stats(*args):
  428.     print 'Report generating functions are in the "pstats" module\x07'
  429.  
  430.  
  431. def main():
  432.     usage = 'profile.py [-o output_file_path] [-s sort] scriptfile [arg] ...'
  433.     parser = OptionParser(usage = usage)
  434.     parser.allow_interspersed_args = False
  435.     parser.add_option('-o', '--outfile', dest = 'outfile', help = 'Save stats to <outfile>', default = None)
  436.     parser.add_option('-s', '--sort', dest = 'sort', help = 'Sort order when printing to stdout, based on pstats.Stats class', default = -1)
  437.     if not sys.argv[1:]:
  438.         parser.print_usage()
  439.         sys.exit(2)
  440.     
  441.     (options, args) = parser.parse_args()
  442.     if len(args) > 0:
  443.         sys.argv[:] = args
  444.         sys.path.insert(0, os.path.dirname(sys.argv[0]))
  445.         run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort)
  446.     else:
  447.         parser.print_usage()
  448.     return parser
  449.  
  450. if __name__ == '__main__':
  451.     main()
  452.  
  453.