Python C扩展的性能分析
我开发了一个Python的C扩展,它可以接收来自Python的数据,并进行一些需要大量计算的操作。请问可以对这个C扩展进行性能分析吗?
这里的问题是,想要写一个可以进行性能分析的C代码示例会比较困难,因为这个代码依赖于特定的输入和数据结构,而这些都是由Python控制代码生成的。
你有什么建议吗?
5 个回答
31
在pygabriel的评论之后,我决定把一个包上传到pypi,这个包是用来给Python扩展做性能分析的,使用的是google-perftools里的cpu-profiler工具:http://pypi.python.org/pypi/yep
22
我找到了使用 google-perftools 的方法。关键是把 StartProfiler 和 StopProfiler 这两个函数用 Python 包裹起来(在我的情况下是通过 cython)。
要分析 C 扩展,只需要把 Python 代码放在 StartProfiler 和 StopProfiler 这两个调用之间就可以了。
from google_perftools_wrapped import StartProfiler, StopProfiler
import c_extension # extension to profile c_extension.so
StartProfiler("output.prof")
... calling the interesting functions from the C extension module ...
StopProfiler()
然后,比如说你可以把结果导出为 callgrind 格式,并在 kcachegrind 中查看结果:
pprof --callgrind c_extension.so output.prof > output.callgrind
kcachegrind output.callgrind