我是一个使用python的完全初学者,每次运行给定的模拟时,我都被要求记录配置文件。我的模拟有4个类和10个循环运行的方法,直到达到某个条件。
我写了创建文件的follow文件:
LOG_FILE = open(os.path.join(os.getcwd(), "logs", "Log_Log_{}.txt".format(
str(datetime.datetime.now()).replace(":", "_"))), mode="w")
在脚本底部我添加了:
if __name__ == "__main__":
cProfile.run("main()", LOG_FILE, sort="tottime")
为什么我的Log_Log文件为空并且cProfile没有返回任何内容?
使用pstats以人类可读的格式转储cProfile的输出
def sample():
# initialize cProfile
profiler_object = cProfile.Profile()
profiler_object.enable()
# execute something here
a = [i for i in range(0, 100)]
profiler_object.disable()
# dump the profiler stats
s = io.StringIO()
ps = pstats.Stats(profiler_object, stream=s).sort_stats('cumulative')
ps.dump_stats('enter your dump file path here')
# convert to human readable format
out_stream = open('enter your log file path here', 'w')
ps = pstats.Stats('enter your dump file path here', stream=out_stream)
ps.strip_dirs().sort_stats('cumulative').print_stats()
return True
sample()
样本输出:
Sat Sep 8 07:07:34 2018 your_dump_file_path
2 function calls in 0.000 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <ipython-input-31-4e18ee895e20>:4(<listcomp>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
你可以通过使用decorators即兴创作
def profiler(func):
def wrapper(*args, **kwargs):
# profiler initialization
res = func(*args, **kwargs)
# further processing
return wrapper
@profiler
def a():
print('hello world')