在已编译的 Cython 代码上使用行分析器(在 ipython 中)

Using the line-profiler (in ipython) on compiled Cython code

我阅读了这个问题的答案 ,但我似乎无法让它与我的设置一起工作。

我有一个 cumsum.pyx 文件:

# cython: profile=True
# cython: linetrace=True
# cython: binding=True
DEF CYTHON_TRACE = 1

def cumulative_sum(int n):
    cdef int s=0, i
    for i in range(n):
        s += i

    return s

我编译它:

cython cumsum.pyx
gcc cumsum.c $(pkg-config --cflags --libs python3) -o cumsum.so -shared -fPIC

然后我尝试在 ipython:

中对其进行分析
%load_ext line_profiler
from cumsum import cumulative_sum
%lprun -f cumulative_sum cumulative_sum(100)

我没有收到错误消息,只有一个空的配置文件:

Timer unit: 1e-06 s

Total time: 0 s
File: cumsum.pyx
Function: cumulative_sum at line 6

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     6                                           def cumulative_sum(int n):
     7                                               cdef int s=0, i
     8                                               for i in range(n):
     9                                                   s += i
    10                                           
    11                                               return s

我怎样才能让它工作?

PS:我使用 CMake,而不是 setup.py,所以我希望能有一个与构建系统无关的解决方案

documentation on Cythons "Profiling" 已经包含一个如何设置 CYTHON_TRACE 宏的示例:

# distutils: define_macros=CYTHON_TRACE_NOGIL=1

而不是你的DEF CYTHON_TRACE = 1

当我使用 %%cython:

编译它时它起作用了
%load_ext cython
%%cython

# cython: profile=True
# cython: linetrace=True
# cython: binding=True
# distutils: define_macros=CYTHON_TRACE_NOGIL=1

def cumulative_sum(int n):
    cdef int s=0, i
    for i in range(n):
        s += i
    return s

并显示分析:

%load_ext line_profiler
%lprun -f cumulative_sum cumulative_sum(100)
[...]
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     7                                           def cumulative_sum(int n):
     8         1            8      8.0      3.5      cdef int s=0, i
     9         1            3      3.0      1.3      for i in range(n):
    10       100          218      2.2     94.4          s += i
    11         1            2      2.0      0.9      return s

原来问题是 DEF CYTHON_TRACE = 1 实际上没有设置正确的常量。

解决方法包括:

1。 MSeifert's answer,使用 distutils

2。 将 gcc 行更改为

gcc cumsum.c $(pkg-config --cflags --libs python3) -o cumsum.so -shared -fPIC -DCYTHON_TRACE=1

3。 制作一个额外的 header trace.h 并在那里设置常量

 #define CYTHON_TRACE 1

同时将以下内容添加到 cumsum.pyx

cdef extern from "trace.h":
    pass

4。 使用 CMake,添加

add_definitions(-DCYTHON_TRACE)