2023年Cython行级性能分析方案咨询:旧方法已失效
Cython行级性能分析可行方案(适配新版环境)
Jupyter Notebook 环境实现步骤
- 安装依赖包
pip install cython line_profiler ipython - 加载Notebook扩展
%load_ext Cython %load_ext line_profiler - 编写带性能分析标记的Cython代码
必须通过@cython.profile(True)装饰器标记要分析的函数,同时在魔法命令中添加-a参数生成分析注释:%cython -a import cython @cython.profile(True) def my_cython_func(int n): cdef int i, sum_val = 0 for i in range(n): sum_val += i return sum_val - 执行行级性能分析
使用%lprun命令指定目标函数并运行:%lprun -f my_cython_func my_cython_func(1000000)
基于cythonize的本地构建实现步骤
- 编写Cython模块文件(
my_module.pyx)
同样用@cython.profile(True)标记目标函数:import cython @cython.profile(True) def my_cython_func(int n): cdef int i, sum_val = 0 for i in range(n): sum_val += i return sum_val - 编写编译配置文件(
setup.py)
在cythonize参数中指定compiler_directives={'profile': True}开启性能分析支持:from setuptools import setup from Cython.Build import cythonize setup( ext_modules=cythonize( "my_module.pyx", compiler_directives={'profile': True} ) ) - 编译安装模块
python setup.py build_ext --inplace - 运行性能分析脚本
from line_profiler import LineProfiler from my_module import my_cython_func lp = LineProfiler() lp_wrap = lp(my_cython_func) lp_wrap(1000000) lp.print_stats()
注意事项
- 确保使用Cython 0.29及以上版本,旧版本的性能分析逻辑已被废弃
- 若函数被编译器自动内联,会导致行级分析无输出,可添加
@cython.inline(False)装饰器禁用内联 - 仅针对带有
cdef/cpdef定义的Cython函数生效,纯Python函数无法通过此方式获得行级分析数据
内容的提问来源于stack exchange,提问作者Mike Battaglia
相关产品推荐
相关产品推荐

