本文整理匯總了Python中hotshot.Profile方法的典型用法代碼示例。如果您正苦於以下問題:Python hotshot.Profile方法的具體用法?Python hotshot.Profile怎麽用?Python hotshot.Profile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類hotshot
的用法示例。
在下文中一共展示了hotshot.Profile方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __call__
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
if self.skip > 0:
self.skip -= 1
self.skipped += 1
return self.fn(*args, **kw)
if FuncProfile.in_profiler:
# handle recursive calls
return self.fn(*args, **kw)
# You cannot reuse the same profiler for many calls and accumulate
# stats that way. :-/
profiler = self.Profile()
try:
FuncProfile.in_profiler = True
return profiler.runcall(self.fn, *args, **kw)
finally:
FuncProfile.in_profiler = False
self.stats.add(profiler)
if self.immediate:
self.print_stats()
self.reset_stats()
示例2: main
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def main(logfile):
p = hotshot.Profile(logfile)
benchtime, stones = p.runcall(test.pystone.pystones)
p.close()
print "Pystone(%s) time for %d passes = %g" % \
(test.pystone.__version__, test.pystone.LOOPS, benchtime)
print "This machine benchmarks at %g pystones/second" % stones
stats = hotshot.stats.load(logfile)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
try:
stats.print_stats(20)
except IOError, e:
if e.errno != errno.EPIPE:
raise
示例3: run_hotshot
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def run_hotshot(filename, profile, args):
prof = hotshot.Profile(profile)
sys.path.insert(0, os.path.dirname(filename))
sys.argv = [filename] + args
prof.run("execfile(%r)" % filename)
prof.close()
stats = hotshot.stats.load(profile)
stats.sort_stats("time", "calls")
# print_stats uses unadorned print statements, so the only way
# to force output to stderr is to reassign sys.stdout temporarily
save_stdout = sys.stdout
sys.stdout = sys.stderr
stats.print_stats()
sys.stdout = save_stdout
return 0
示例4: __init__
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def __init__(self, fn, skip=0, filename=None):
"""Creates a profiler for a function.
Every profiler has its own log file (the name of which is derived
from the function name).
HotShotFuncProfile registers an atexit handler that prints
profiling information to sys.stderr when the program terminates.
The log file is not removed and remains there to clutter the
current working directory.
"""
self.fn = fn
self.filename = filename
if self.filename:
self.logfilename = filename + ".raw"
else:
self.logfilename = fn.__name__ + ".prof"
self.profiler = hotshot.Profile(self.logfilename)
self.ncalls = 0
self.skip = skip
self.skipped = 0
atexit.register(self.atexit)
示例5: runMain
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def runMain(main, options, args):
if options.profile:
if True:
import hotshot
profile = hotshot.Profile(options.profile)
profile.runcall(main, options, args)
profile.close()
import hotshot.stats
stats = hotshot.stats.load(options.profile)
else:
import profile
profile.run('main(options, args)', options.profile)
import pstats
stats = pstats.Stats(options.profile)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(20)
elif options.psyco:
import psyco
psyco.full()
status = main(options, args)
else:
status = main(options, args)
return status
示例6: handler
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def handler(req):
'''
Handler that uses hotshot to store profile data.
Stores profile data in PROFILE_DATA_DIR. Since hotshot has no way (that I
know of) to append profile data to a single file, each request gets its own
profile. The file names are in the format <url>.<n>.prof where <url> is
the request path with "/" replaced by ".", and <n> is a timestamp with
microseconds to prevent overwriting files.
Use the gather_profile_stats.py script to gather these individual request
profiles into aggregated profiles by request path.
'''
profname = "%s.%.3f.prof" % (req.uri.strip("/").replace('/', '.'), time.time())
profname = os.path.join(PROFILE_DATA_DIR, profname)
prof = hotshot.Profile(profname)
return prof.runcall(ModPythonHandler(), req)
示例7: runProfiler
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def runProfiler(logger, func, args=tuple(), kw={}, verbose=True, nb_func=25, sort_by=('cumulative', 'calls')):
profile_filename = "/tmp/profiler"
prof = Profile(profile_filename)
try:
logger.warning("Run profiler")
result = prof.runcall(func, *args, **kw)
prof.close()
logger.error("Profiler: Process data...")
stat = loadStats(profile_filename)
stat.strip_dirs()
stat.sort_stats(*sort_by)
logger.error("Profiler: Result:")
log = StringIO()
stat.stream = log
stat.print_stats(nb_func)
log.seek(0)
for line in log:
logger.error(line.rstrip())
return result
finally:
unlink(profile_filename)
示例8: prof_main
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def prof_main(argv):
import hotshot, hotshot.stats
def usage():
print(('usage: %s module.function [args ...]' % argv[0]))
return 100
args = argv[1:]
if len(args) < 1: return usage()
name = args.pop(0)
prof = name+'.prof'
i = name.rindex('.')
(modname, funcname) = (name[:i], name[i+1:])
module = __import__(modname, fromlist=1)
func = getattr(module, funcname)
if args:
args.insert(0, argv[0])
prof = hotshot.Profile(prof)
prof.runcall(lambda : func(args))
prof.close()
else:
stats = hotshot.stats.load(prof)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(1000)
return
示例9: runTest
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def runTest(self):
self.prof = hotshot.Profile('%s.prof' % self.__class__.__name__)
self.prof.start()
for i in range(self.iterations):
if hasattr(self, 'performanceSample'):
self.display = True
self.performanceSample()
self.prof.stop()
self.prof.close()
if self.display:
print('>>> %s (%d iterations) ' % (self.__class__.__name__,
self.iterations))
stats = hotshot.stats.load('%s.prof' % self.__class__.__name__)
#stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(50)
if not self.save:
os.unlink('%s.prof' % self.__class__.__name__)
示例10: reset_stats
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def reset_stats(self):
"""Reset accumulated profiler statistics."""
# Note: not using self.Profile, since pstats.Stats() fails then
self.stats = pstats.Stats(Profile())
self.ncalls = 0
self.skipped = 0
示例11: print_stats
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def print_stats(self):
if self.profiler is None:
self.stats = pstats.Stats(Profile())
else:
self.profiler.close()
self.stats = hotshot.stats.load(self.logfilename)
super(HotShotFuncProfile, self).print_stats()
示例12: process_request
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def process_request(self, request):
if (settings.DEBUG or request.user.is_superuser) and 'prof' in request.GET:
self.tmpfile = tempfile.mktemp()
self.prof = hotshot.Profile(self.tmpfile)
示例13: profile
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def profile(log_file):
"""Profile some callable.
This decorator uses the hotshot profiler to profile some callable (like
a view function or method) and dumps the profile data somewhere sensible
for later processing and examination.
It takes one argument, the profile log name. If it's a relative path, it
places it under the PROFILE_LOG_BASE. It also inserts a time stamp into the
file name, such that 'my_view.prof' become 'my_view-20100211T170321.prof',
where the time stamp is in UTC. This makes it easy to run and compare
multiple trials.
"""
if not os.path.isabs(log_file):
log_file = os.path.join(PROFILE_LOG_BASE, log_file)
def _outer(f):
def _inner(*args, **kwargs):
# Add a timestamp to the profile output when the callable
# is actually called.
(base, ext) = os.path.splitext(log_file)
base = base + "-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime())
final_log_file = base + ext
prof = hotshot.Profile(final_log_file)
try:
ret = prof.runcall(f, *args, **kwargs)
finally:
prof.close()
return ret
return _inner
return _outer
示例14: __call__
# 需要導入模塊: import hotshot [as 別名]
# 或者: from hotshot import Profile [as 別名]
def __call__(self, environ, start_response):
catch_response = []
body = []
def replace_start_response(status, headers, exc_info=None):
catch_response.extend([status, headers])
start_response(status, headers, exc_info)
return body.append
def run_app():
app_iter = self.app(environ, replace_start_response)
try:
body.extend(app_iter)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
self.lock.acquire()
try:
prof = hotshot.Profile(self.log_filename)
prof.addinfo('URL', environ.get('PATH_INFO', ''))
try:
prof.runcall(run_app)
finally:
prof.close()
body = ''.join(body)
headers = catch_response[1]
content_type = response.header_value(headers, 'content-type')
if content_type is None or not content_type.startswith('text/html'):
# We can't add info to non-HTML output
return [body]
stats = hotshot.stats.load(self.log_filename)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
output = capture_output(stats.print_stats, self.limit)
output_callers = capture_output(
stats.print_callers, self.limit)
body += '<pre style="%s">%s\n%s</pre>' % (
self.style, cgi.escape(output), cgi.escape(output_callers))
return [body]
finally:
self.lock.release()