+++ /dev/null
-#! /usr/bin/env python\r
-\r
-"""Python interface for the 'lsprof' profiler.\r
- Compatible with the 'profile' module.\r
-"""\r
-\r
-__all__ = ["run", "runctx", "help", "Profile"]\r
-\r
-import _lsprof\r
-\r
-# ____________________________________________________________\r
-# Simple interface\r
-\r
-def run(statement, filename=None, sort=-1):\r
- """Run statement under profiler optionally saving results in filename\r
-\r
- This function takes a single argument that can be passed to the\r
- "exec" statement, and an optional file name. In all cases this\r
- routine attempts to "exec" its first argument and gather profiling\r
- statistics from the execution. If no file name is present, then this\r
- function automatically prints a simple profiling report, sorted by the\r
- standard name string (file/line/function-name) that is presented in\r
- each line.\r
- """\r
- prof = Profile()\r
- result = None\r
- try:\r
- try:\r
- prof = prof.run(statement)\r
- except SystemExit:\r
- pass\r
- finally:\r
- if filename is not None:\r
- prof.dump_stats(filename)\r
- else:\r
- result = prof.print_stats(sort)\r
- return result\r
-\r
-def runctx(statement, globals, locals, filename=None, sort=-1):\r
- """Run statement under profiler, supplying your own globals and locals,\r
- optionally saving results in filename.\r
-\r
- statement and filename have the same semantics as profile.run\r
- """\r
- prof = Profile()\r
- result = None\r
- try:\r
- try:\r
- prof = prof.runctx(statement, globals, locals)\r
- except SystemExit:\r
- pass\r
- finally:\r
- if filename is not None:\r
- prof.dump_stats(filename)\r
- else:\r
- result = prof.print_stats(sort)\r
- return result\r
-\r
-# Backwards compatibility.\r
-def help():\r
- print "Documentation for the profile/cProfile modules can be found "\r
- print "in the Python Library Reference, section 'The Python Profiler'."\r
-\r
-# ____________________________________________________________\r
-\r
-class Profile(_lsprof.Profiler):\r
- """Profile(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\r
-\r
- Builds a profiler object using the specified timer function.\r
- The default timer is a fast built-in one based on real time.\r
- For custom timer functions returning integers, time_unit can\r
- be a float specifying a scale (i.e. how long each integer unit\r
- is, in seconds).\r
- """\r
-\r
- # Most of the functionality is in the base class.\r
- # This subclass only adds convenient and backward-compatible methods.\r
-\r
- def print_stats(self, sort=-1):\r
- import pstats\r
- pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()\r
-\r
- def dump_stats(self, file):\r
- import marshal\r
- f = open(file, 'wb')\r
- self.create_stats()\r
- marshal.dump(self.stats, f)\r
- f.close()\r
-\r
- def create_stats(self):\r
- self.disable()\r
- self.snapshot_stats()\r
-\r
- def snapshot_stats(self):\r
- entries = self.getstats()\r
- self.stats = {}\r
- callersdicts = {}\r
- # call information\r
- for entry in entries:\r
- func = label(entry.code)\r
- nc = entry.callcount # ncalls column of pstats (before '/')\r
- cc = nc - entry.reccallcount # ncalls column of pstats (after '/')\r
- tt = entry.inlinetime # tottime column of pstats\r
- ct = entry.totaltime # cumtime column of pstats\r
- callers = {}\r
- callersdicts[id(entry.code)] = callers\r
- self.stats[func] = cc, nc, tt, ct, callers\r
- # subcall information\r
- for entry in entries:\r
- if entry.calls:\r
- func = label(entry.code)\r
- for subentry in entry.calls:\r
- try:\r
- callers = callersdicts[id(subentry.code)]\r
- except KeyError:\r
- continue\r
- nc = subentry.callcount\r
- cc = nc - subentry.reccallcount\r
- tt = subentry.inlinetime\r
- ct = subentry.totaltime\r
- if func in callers:\r
- prev = callers[func]\r
- nc += prev[0]\r
- cc += prev[1]\r
- tt += prev[2]\r
- ct += prev[3]\r
- callers[func] = nc, cc, tt, ct\r
-\r
- # The following two methods can be called by clients to use\r
- # a profiler to profile a statement, given as a string.\r
-\r
- def run(self, cmd):\r
- import __main__\r
- dict = __main__.__dict__\r
- return self.runctx(cmd, dict, dict)\r
-\r
- def runctx(self, cmd, globals, locals):\r
- self.enable()\r
- try:\r
- exec cmd in globals, locals\r
- finally:\r
- self.disable()\r
- return self\r
-\r
- # This method is more useful to profile a single function call.\r
- def runcall(self, func, *args, **kw):\r
- self.enable()\r
- try:\r
- return func(*args, **kw)\r
- finally:\r
- self.disable()\r
-\r
-# ____________________________________________________________\r
-\r
-def label(code):\r
- if isinstance(code, str):\r
- return ('~', 0, code) # built-in functions ('~' sorts at the end)\r
- else:\r
- return (code.co_filename, code.co_firstlineno, code.co_name)\r
-\r
-# ____________________________________________________________\r
-\r
-def main():\r
- import os, sys\r
- from optparse import OptionParser\r
- usage = "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."\r
- parser = OptionParser(usage=usage)\r
- parser.allow_interspersed_args = False\r
- parser.add_option('-o', '--outfile', dest="outfile",\r
- help="Save stats to <outfile>", default=None)\r
- parser.add_option('-s', '--sort', dest="sort",\r
- help="Sort order when printing to stdout, based on pstats.Stats class",\r
- default=-1)\r
-\r
- if not sys.argv[1:]:\r
- parser.print_usage()\r
- sys.exit(2)\r
-\r
- (options, args) = parser.parse_args()\r
- sys.argv[:] = args\r
-\r
- if len(args) > 0:\r
- progname = args[0]\r
- sys.path.insert(0, os.path.dirname(progname))\r
- with open(progname, 'rb') as fp:\r
- code = compile(fp.read(), progname, 'exec')\r
- globs = {\r
- '__file__': progname,\r
- '__name__': '__main__',\r
- '__package__': None,\r
- }\r
- runctx(code, globs, None, options.outfile, options.sort)\r
- else:\r
- parser.print_usage()\r
- return parser\r
-\r
-# When invoked as main program, invoke the profiler on a script\r
-if __name__ == '__main__':\r
- main()\r