home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / profile.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  12.3 KB  |  429 lines

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