return self._calibrate_inner(m, verbose)
def _calibrate_inner(self, m, verbose):
# Set up a test case to be run with and without profiling. Include
# lots of calls, because we're trying to quantify stopwatch overhead.
# Do not raise any exceptions, though, because we want to know
# exactly how many profile events are generated (one call event, +
# one return event, per Python-level call).
# elapsed_noprofile <- time f(m) takes without profiling.
elapsed_noprofile = t1 - t0
print("elapsed time without profiling =", elapsed_noprofile)
# elapsed_profile <- time f(m) takes with profiling. The difference
# is profiling overhead, only some of which the profiler subtracts
p.runctx('f(m)', globals(), locals())
elapsed_profile = t1 - t0
print("elapsed time with profiling =", elapsed_profile)
# reported_time <- "CPU seconds" the profiler charged to f and f1.
for (filename, line, funcname), (cc, ns, tt, ct, callers) in \
if funcname in ("f", "f1"):
print("'CPU seconds' profiler reported =", reported_time)
print("total # calls =", total_calls)
raise ValueError("internal error: total calls = %d" % total_calls)
# reported_time - elapsed_noprofile = overhead the profiler wasn't
# able to measure. Divide by twice the number of calls (since there
# are two profiler events per call in this test) to get the hidden
mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
print("mean stopwatch overhead per profile event =", mean)
#****************************************************************************
from optparse import OptionParser
usage = "profile.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('-m', dest="module", action="store_true",
help="Profile a library module.", default=False)
parser.add_option('-s', '--sort', dest="sort",
help="Sort order when printing to stdout, based on pstats.Stats class",
(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 io.open_code(progname) 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__':