我已经找到了使用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