3 """Python interface for the 'lsprof' profiler.
4 Compatible with the 'profile' module.
7 __all__
= ["run", "runctx", "help", "Profile"]
11 # ____________________________________________________________
14 def run(statement
, filename
=None, sort
=-1):
15 """Run statement under profiler optionally saving results in filename
17 This function takes a single argument that can be passed to the
18 "exec" statement, and an optional file name. In all cases this
19 routine attempts to "exec" its first argument and gather profiling
20 statistics from the execution. If no file name is present, then this
21 function automatically prints a simple profiling report, sorted by the
22 standard name string (file/line/function-name) that is presented in
29 prof
= prof
.run(statement
)
33 if filename
is not None:
34 prof
.dump_stats(filename
)
36 result
= prof
.print_stats(sort
)
39 def runctx(statement
, globals, locals, filename
=None):
40 """Run statement under profiler, supplying your own globals and locals,
41 optionally saving results in filename.
43 statement and filename have the same semantics as profile.run
49 prof
= prof
.runctx(statement
, globals, locals)
53 if filename
is not None:
54 prof
.dump_stats(filename
)
56 result
= prof
.print_stats()
59 # Backwards compatibility.
61 print "Documentation for the profile/cProfile modules can be found "
62 print "in the Python Library Reference, section 'The Python Profiler'."
64 # ____________________________________________________________
66 class Profile(_lsprof
.Profiler
):
67 """Profile(custom_timer=None, time_unit=None, subcalls=True, builtins=True)
69 Builds a profiler object using the specified timer function.
70 The default timer is a fast built-in one based on real time.
71 For custom timer functions returning integers, time_unit can
72 be a float specifying a scale (i.e. how long each integer unit
76 # Most of the functionality is in the base class.
77 # This subclass only adds convenient and backward-compatible methods.
79 def print_stats(self
, sort
=-1):
81 pstats
.Stats(self
).strip_dirs().sort_stats(sort
).print_stats()
83 def dump_stats(self
, file):
87 marshal
.dump(self
.stats
, f
)
90 def create_stats(self
):
94 def snapshot_stats(self
):
95 entries
= self
.getstats()
100 func
= label(entry
.code
)
101 nc
= entry
.callcount
# ncalls column of pstats (before '/')
102 cc
= nc
- entry
.reccallcount
# ncalls column of pstats (after '/')
103 tt
= entry
.inlinetime
# tottime column of pstats
104 ct
= entry
.totaltime
# cumtime column of pstats
106 callersdicts
[id(entry
.code
)] = callers
107 self
.stats
[func
] = cc
, nc
, tt
, ct
, callers
108 # subcall information
109 for entry
in entries
:
111 func
= label(entry
.code
)
112 for subentry
in entry
.calls
:
114 callers
= callersdicts
[id(subentry
.code
)]
117 nc
= subentry
.callcount
118 cc
= nc
- subentry
.reccallcount
119 tt
= subentry
.inlinetime
120 ct
= subentry
.totaltime
127 callers
[func
] = nc
, cc
, tt
, ct
129 # The following two methods can be called by clients to use
130 # a profiler to profile a statement, given as a string.
134 dict = __main__
.__dict
__
135 return self
.runctx(cmd
, dict, dict)
137 def runctx(self
, cmd
, globals, locals):
140 exec cmd
in globals, locals
145 # This method is more useful to profile a single function call.
146 def runcall(self
, func
, *args
, **kw
):
149 return func(*args
, **kw
)
153 # ____________________________________________________________
156 if isinstance(code
, str):
157 return ('~', 0, code
) # built-in functions ('~' sorts at the end)
159 return (code
.co_filename
, code
.co_firstlineno
, code
.co_name
)
161 # ____________________________________________________________
165 from optparse
import OptionParser
166 usage
= "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
167 parser
= OptionParser(usage
=usage
)
168 parser
.allow_interspersed_args
= False
169 parser
.add_option('-o', '--outfile', dest
="outfile",
170 help="Save stats to <outfile>", default
=None)
171 parser
.add_option('-s', '--sort', dest
="sort",
172 help="Sort order when printing to stdout, based on pstats.Stats class", default
=-1)
178 (options
, args
) = parser
.parse_args()
181 if (len(sys
.argv
) > 0):
182 sys
.path
.insert(0, os
.path
.dirname(sys
.argv
[0]))
183 run('execfile(%r)' % (sys
.argv
[0],), options
.outfile
, options
.sort
)
188 # When invoked as main program, invoke the profiler on a script
189 if __name__
== '__main__':