]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | #! /usr/bin/env python\r |
2 | \r | |
3 | """Python interface for the 'lsprof' profiler.\r | |
4 | Compatible with the 'profile' module.\r | |
5 | """\r | |
6 | \r | |
7 | __all__ = ["run", "runctx", "help", "Profile"]\r | |
8 | \r | |
9 | import _lsprof\r | |
10 | \r | |
11 | # ____________________________________________________________\r | |
12 | # Simple interface\r | |
13 | \r | |
14 | def run(statement, filename=None, sort=-1):\r | |
15 | """Run statement under profiler optionally saving results in filename\r | |
16 | \r | |
17 | This function takes a single argument that can be passed to the\r | |
18 | "exec" statement, and an optional file name. In all cases this\r | |
19 | routine attempts to "exec" its first argument and gather profiling\r | |
20 | statistics from the execution. If no file name is present, then this\r | |
21 | function automatically prints a simple profiling report, sorted by the\r | |
22 | standard name string (file/line/function-name) that is presented in\r | |
23 | each line.\r | |
24 | """\r | |
25 | prof = Profile()\r | |
26 | result = None\r | |
27 | try:\r | |
28 | try:\r | |
29 | prof = prof.run(statement)\r | |
30 | except SystemExit:\r | |
31 | pass\r | |
32 | finally:\r | |
33 | if filename is not None:\r | |
34 | prof.dump_stats(filename)\r | |
35 | else:\r | |
36 | result = prof.print_stats(sort)\r | |
37 | return result\r | |
38 | \r | |
39 | def runctx(statement, globals, locals, filename=None, sort=-1):\r | |
40 | """Run statement under profiler, supplying your own globals and locals,\r | |
41 | optionally saving results in filename.\r | |
42 | \r | |
43 | statement and filename have the same semantics as profile.run\r | |
44 | """\r | |
45 | prof = Profile()\r | |
46 | result = None\r | |
47 | try:\r | |
48 | try:\r | |
49 | prof = prof.runctx(statement, globals, locals)\r | |
50 | except SystemExit:\r | |
51 | pass\r | |
52 | finally:\r | |
53 | if filename is not None:\r | |
54 | prof.dump_stats(filename)\r | |
55 | else:\r | |
56 | result = prof.print_stats(sort)\r | |
57 | return result\r | |
58 | \r | |
59 | # Backwards compatibility.\r | |
60 | def help():\r | |
61 | print "Documentation for the profile/cProfile modules can be found "\r | |
62 | print "in the Python Library Reference, section 'The Python Profiler'."\r | |
63 | \r | |
64 | # ____________________________________________________________\r | |
65 | \r | |
66 | class Profile(_lsprof.Profiler):\r | |
67 | """Profile(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\r | |
68 | \r | |
69 | Builds a profiler object using the specified timer function.\r | |
70 | The default timer is a fast built-in one based on real time.\r | |
71 | For custom timer functions returning integers, time_unit can\r | |
72 | be a float specifying a scale (i.e. how long each integer unit\r | |
73 | is, in seconds).\r | |
74 | """\r | |
75 | \r | |
76 | # Most of the functionality is in the base class.\r | |
77 | # This subclass only adds convenient and backward-compatible methods.\r | |
78 | \r | |
79 | def print_stats(self, sort=-1):\r | |
80 | import pstats\r | |
81 | pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()\r | |
82 | \r | |
83 | def dump_stats(self, file):\r | |
84 | import marshal\r | |
85 | f = open(file, 'wb')\r | |
86 | self.create_stats()\r | |
87 | marshal.dump(self.stats, f)\r | |
88 | f.close()\r | |
89 | \r | |
90 | def create_stats(self):\r | |
91 | self.disable()\r | |
92 | self.snapshot_stats()\r | |
93 | \r | |
94 | def snapshot_stats(self):\r | |
95 | entries = self.getstats()\r | |
96 | self.stats = {}\r | |
97 | callersdicts = {}\r | |
98 | # call information\r | |
99 | for entry in entries:\r | |
100 | func = label(entry.code)\r | |
101 | nc = entry.callcount # ncalls column of pstats (before '/')\r | |
102 | cc = nc - entry.reccallcount # ncalls column of pstats (after '/')\r | |
103 | tt = entry.inlinetime # tottime column of pstats\r | |
104 | ct = entry.totaltime # cumtime column of pstats\r | |
105 | callers = {}\r | |
106 | callersdicts[id(entry.code)] = callers\r | |
107 | self.stats[func] = cc, nc, tt, ct, callers\r | |
108 | # subcall information\r | |
109 | for entry in entries:\r | |
110 | if entry.calls:\r | |
111 | func = label(entry.code)\r | |
112 | for subentry in entry.calls:\r | |
113 | try:\r | |
114 | callers = callersdicts[id(subentry.code)]\r | |
115 | except KeyError:\r | |
116 | continue\r | |
117 | nc = subentry.callcount\r | |
118 | cc = nc - subentry.reccallcount\r | |
119 | tt = subentry.inlinetime\r | |
120 | ct = subentry.totaltime\r | |
121 | if func in callers:\r | |
122 | prev = callers[func]\r | |
123 | nc += prev[0]\r | |
124 | cc += prev[1]\r | |
125 | tt += prev[2]\r | |
126 | ct += prev[3]\r | |
127 | callers[func] = nc, cc, tt, ct\r | |
128 | \r | |
129 | # The following two methods can be called by clients to use\r | |
130 | # a profiler to profile a statement, given as a string.\r | |
131 | \r | |
132 | def run(self, cmd):\r | |
133 | import __main__\r | |
134 | dict = __main__.__dict__\r | |
135 | return self.runctx(cmd, dict, dict)\r | |
136 | \r | |
137 | def runctx(self, cmd, globals, locals):\r | |
138 | self.enable()\r | |
139 | try:\r | |
140 | exec cmd in globals, locals\r | |
141 | finally:\r | |
142 | self.disable()\r | |
143 | return self\r | |
144 | \r | |
145 | # This method is more useful to profile a single function call.\r | |
146 | def runcall(self, func, *args, **kw):\r | |
147 | self.enable()\r | |
148 | try:\r | |
149 | return func(*args, **kw)\r | |
150 | finally:\r | |
151 | self.disable()\r | |
152 | \r | |
153 | # ____________________________________________________________\r | |
154 | \r | |
155 | def label(code):\r | |
156 | if isinstance(code, str):\r | |
157 | return ('~', 0, code) # built-in functions ('~' sorts at the end)\r | |
158 | else:\r | |
159 | return (code.co_filename, code.co_firstlineno, code.co_name)\r | |
160 | \r | |
161 | # ____________________________________________________________\r | |
162 | \r | |
163 | def main():\r | |
164 | import os, sys\r | |
165 | from optparse import OptionParser\r | |
166 | usage = "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."\r | |
167 | parser = OptionParser(usage=usage)\r | |
168 | parser.allow_interspersed_args = False\r | |
169 | parser.add_option('-o', '--outfile', dest="outfile",\r | |
170 | help="Save stats to <outfile>", default=None)\r | |
171 | parser.add_option('-s', '--sort', dest="sort",\r | |
172 | help="Sort order when printing to stdout, based on pstats.Stats class",\r | |
173 | default=-1)\r | |
174 | \r | |
175 | if not sys.argv[1:]:\r | |
176 | parser.print_usage()\r | |
177 | sys.exit(2)\r | |
178 | \r | |
179 | (options, args) = parser.parse_args()\r | |
180 | sys.argv[:] = args\r | |
181 | \r | |
182 | if len(args) > 0:\r | |
183 | progname = args[0]\r | |
184 | sys.path.insert(0, os.path.dirname(progname))\r | |
185 | with open(progname, 'rb') as fp:\r | |
186 | code = compile(fp.read(), progname, 'exec')\r | |
187 | globs = {\r | |
188 | '__file__': progname,\r | |
189 | '__name__': '__main__',\r | |
190 | '__package__': None,\r | |
191 | }\r | |
192 | runctx(code, globs, None, options.outfile, options.sort)\r | |
193 | else:\r | |
194 | parser.print_usage()\r | |
195 | return parser\r | |
196 | \r | |
197 | # When invoked as main program, invoke the profiler on a script\r | |
198 | if __name__ == '__main__':\r | |
199 | main()\r |