Python C扩展的性能分析

48 投票
5 回答
11977 浏览
提问于 2025-04-15 21:28

我开发了一个Python的C扩展,它可以接收来自Python的数据,并进行一些需要大量计算的操作。请问可以对这个C扩展进行性能分析吗?

这里的问题是,想要写一个可以进行性能分析的C代码示例会比较困难,因为这个代码依赖于特定的输入和数据结构,而这些都是由Python控制代码生成的。

你有什么建议吗?

5 个回答

8

我发现 py-spy 非常好用。想了解它如何支持本地扩展,可以看看 这篇博客

主要特点:

  • 可以通过 pip 安装
  • 基于 CPU 采样
  • 不需要编译器标志
  • 可以执行你的程序或者连接到正在运行的进程
  • 支持多种输出格式(我推荐使用 --format speedscope
  • 可以设置采样频率
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

撰写回答