#! /usr/libexec/platform-python -s
"""Python interface for the 'lsprof' profiler.
Compatible with the 'profile' module.
__all__ = ["run", "runctx", "Profile"]
import profile as _pyprofile
# ____________________________________________________________
def run(statement, filename=None, sort=-1):
return _pyprofile._Utils(Profile).run(statement, filename, sort)
def runctx(statement, globals, locals, filename=None, sort=-1):
return _pyprofile._Utils(Profile).runctx(statement, globals, locals,
run.__doc__ = _pyprofile.run.__doc__
runctx.__doc__ = _pyprofile.runctx.__doc__
# ____________________________________________________________
class Profile(_lsprof.Profiler):
"""Profile(timer=None, timeunit=None, subcalls=True, builtins=True)
Builds a profiler object using the specified timer function.
The default timer is a fast built-in one based on real time.
For custom timer functions returning integers, timeunit can
be a float specifying a scale (i.e. how long each integer unit
# Most of the functionality is in the base class.
# This subclass only adds convenient and backward-compatible methods.
def print_stats(self, sort=-1):
pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
def dump_stats(self, file):
with open(file, 'wb') as f:
marshal.dump(self.stats, f)
def snapshot_stats(self):
entries = self.getstats()
nc = entry.callcount # ncalls column of pstats (before '/')
cc = nc - entry.reccallcount # ncalls column of pstats (after '/')
tt = entry.inlinetime # tottime column of pstats
ct = entry.totaltime # cumtime column of pstats
callersdicts[id(entry.code)] = callers
self.stats[func] = cc, nc, tt, ct, callers
for subentry in entry.calls:
callers = callersdicts[id(subentry.code)]
cc = nc - subentry.reccallcount
callers[func] = nc, cc, tt, ct
# The following two methods can be called by clients to use
# a profiler to profile a statement, given as a string.
return self.runctx(cmd, dict, dict)
def runctx(self, cmd, globals, locals):
exec(cmd, globals, locals)
# This method is more useful to profile a single function call.
def runcall(self, func, /, *args, **kw):
def __exit__(self, *exc_info):
# ____________________________________________________________
if isinstance(code, str):
return ('~', 0, code) # built-in functions ('~' sorts at the end)
return (code.co_filename, code.co_firstlineno, code.co_name)
# ____________________________________________________________
from optparse import OptionParser
usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..."
parser = OptionParser(usage=usage)
parser.allow_interspersed_args = False
parser.add_option('-o', '--outfile', dest="outfile",
help="Save stats to <outfile>", default=None)
parser.add_option('-s', '--sort', dest="sort",
help="Sort order when printing to stdout, based on pstats.Stats class",
choices=sorted(pstats.Stats.sort_arg_dict_default))
parser.add_option('-m', dest="module", action="store_true",
help="Profile a library module", default=False)
(options, args) = parser.parse_args()
# The script that we're profiling may chdir, so capture the absolute path
# to the output file at startup.
if options.outfile is not None:
options.outfile = os.path.abspath(options.outfile)
code = "run_module(modname, run_name='__main__')"
'run_module': runpy.run_module,
sys.path.insert(0, os.path.dirname(progname))
with open(progname, 'rb') as fp:
code = compile(fp.read(), progname, 'exec')
runctx(code, globs, None, options.outfile, options.sort)
except BrokenPipeError as exc:
# Prevent "Exception ignored" during interpreter shutdown.
# When invoked as main program, invoke the profiler on a script
if __name__ == '__main__':