在KCacheGrind中使用cProfile结果
我正在使用cProfile来分析我的Python程序的性能。根据这场讲座,我以为KCacheGrind可以解析并显示cProfile的输出结果。
但是,当我尝试导入文件时,KCacheGrind在状态栏上显示“未知文件格式”的错误,并且什么都不显示。
在我的分析统计数据与KCacheGrind兼容之前,我需要做些什么特别的事情吗?
...
if profile:
import cProfile
profileFileName = 'Profiles/pythonray_' + time.strftime('%Y%m%d_%H%M%S') + '.profile'
profile = cProfile.Profile()
profile.run('pilImage = camera.render(scene, samplePattern)')
profile.dump_stats(profileFileName)
profile.print_stats()
else:
pilImage = camera.render(scene, samplePattern)
...
软件包版本
- KCacheGrind 4.3.1
- Python 2.6.2
5 个回答
17
你可以使用 profilestats.profile
这个装饰器($ pip install profilestats
来安装)——它其实是一个简单的包装工具,用于 pyprof2calltree 模块(这个模块是 lsprofcalltree.py
的新名字)。
from profilestats import profile
@profile
def func():
# do something here
你可以像平常一样运行脚本。profilestats
会生成两个文件:cachegrind.out.profilestats
和 profilestats.prof
,分别是 KCachegrind 兼容格式和 cProfile 格式。
96
使用cProfile,你可以对现有的程序进行性能分析,而不需要单独写一个分析脚本。只需用分析工具运行程序就可以了。
python -m cProfile -o profile_data.pyprof script_to_profile.py
然后用pyprof2calltree把分析数据打开在kcachegrind里,-k这个选项可以自动在kcachegrind中打开数据。
pyprof2calltree -i profile_data.pyprof -k
比如,要对整个paster服务器和网页应用进行分析,可以这样做:
python -m cProfile -o pyprof.out `which paster` serve development.ini
pyprof2calltree可以通过easy_install来安装。
7
可以通过一个叫做 lscallproftree 的外部模块来实现这个功能。
这篇文章解释了具体怎么做: CherryPy - CacheGrind
我的代码看起来是这样的:
...
if profile:
import cProfile
import lsprofcalltree
profileFileName = 'Profiles/pythonray_' + time.strftime('%Y%m%d_%H%M%S') + '.profile'
profile = cProfile.Profile()
profile.run('pilImage = camera.render(scene, samplePattern)')
kProfile = lsprofcalltree.KCacheGrind(profile)
kFile = open (profileFileName, 'w+')
kProfile.output(kFile)
kFile.close()
profile.print_stats()
else:
pilImage = camera.render(scene, samplePattern)
...
如果有人知道不需要外部模块(也就是说,不是随Python一起提供的模块)的方法,我也很想听听。