我正在尝试连续调用一些分析器代码,但是在第二次调用该函数时,配置文件的更新时间发生了变化,但实际的分析器统计数据保持不变。这不是我正在运行的代码,但它是我能想出的显示相同行为的简化示例。
在运行时,第一次按下ctrl+c时,它会显示统计信息,第二次显示相同的内容,但没有像预期的那样完全更新,只有时间是这样,第三次程序实际上退出了。如果尝试,最好在按ctrl+c键之间等待几秒钟。
在第8行之后添加profiler.enable()确实会在两次调用之间进行完全更新,但是它会为我不希望分析的内容添加大量额外的分析器数据。
有什么建议可以让我得到完整的更新,但没有额外的混乱吗?
import signal, sys, time, cProfile, pstats
call = 0
def sigint_handler(signal, frame):
global call
if call < 2:
profiler.dump_stats("profile.prof")
stats = pstats.Stats("profile.prof")
stats.strip_dirs().sort_stats('cumulative').print_stats()
call += 1
else:
sys.exit()
def wait():
time.sleep(1)
def main_io_loop():
signal.signal(signal.SIGINT, sigint_handler)
while 1:
wait()
profiler = cProfile.Profile()
profiler.runctx("main_io_loop()", globals(), locals())发布于 2009-02-23 00:37:42
调用profiler.dump_stats (在cProfile.py中实现)会调用profiler.create_stats,而后者又会调用profiler.disable()。
您需要调用profiler.enable()才能使其再次工作。不,这没有记录在案。
下面的代码似乎可以做你想做的事情。注意,我去掉了中间数据文件,因为pstats.Stats知道如何直接从分析器获取数据。
import signal, sys, time, pstats, cProfile
call = 0
def sigint_handler(signal, frame):
global call
if call < 2:
stats = pstats.Stats(profiler)
stats.strip_dirs().sort_stats('cumulative').print_stats()
profiler.enable()
call += 1
else:
sys.exit()
def wait():
time.sleep(1)
def main_io_loop():
signal.signal(signal.SIGINT, sigint_handler)
while 1:
wait()
profiler = cProfile.Profile()
profiler.runctx("main_io_loop()", globals(), locals())https://stackoverflow.com/questions/575325
复制相似问题