第十六章:开发工具-profile和pstats:性能分析-pstats:保存和处理统计信息

it2022-05-05  103

16.8.3 pstats:保存和处理统计信息 profile函数创建的标准报告不太灵活。不过,可以保存run()和runctx()的原始性能数据并用pstats.Stats类单独处理,以生成定制报告。 下面的例子会多次迭代运行同一个测试,并且合并该结果。

import cProfile as profile import pstats from profile_fibonacci_memoized import fib,fib_seq # Create 5 sets of stats. for i in range(5): filename = 'profile_stats_{}.stats'.format(i) profile.run('print({},fib_seq(20))'.format(i),filename) # Read all 5 stats files into a single object. stats = pstats.Stats('profile_stats_0.stats') for i in range(1,5): stats.add('profile_stats_{}.stats'.format(i)) # Clean up filenames for the report. stats.strip_dirs() # Sort the statistics by the cumulative time spent # in the function. stats.sort_stats('cumulative') stats.print_stats()

输出报告按其在函数中所花费的累积时间的降序排序,另外打印的文件名中去掉了目录名,以节省页面上的水平空间。


最新回复(0)