3

我阅读了这个问题的答案How to profile cython functions line-by-line,但我似乎无法让它与我的设置一起使用。

我有一个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,所以我会很感激构建系统不可知的解决方案

4

2 回答 2

1

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
于 2017-01-29T22:05:52.547 回答
0

原来问题在于DEF CYTHON_TRACE = 1它实际上并没有设置正确的常数。

解决方法包括:

1. MSeifert 的回答,使用 distutils

2. 将 gcc 行更改为

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

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

 #define CYTHON_TRACE 1

以及将以下内容添加到cumsum.pyx

cdef extern from "trace.h":
    pass

4.使用CMake,添加

add_definitions(-DCYTHON_TRACE)
于 2017-01-29T22:56:21.730 回答