gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:25:10 25 4
gpt4 key购买 nike

我看了这个问题的答案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,所以我希望能有一个与构建系统无关的解决方案

最佳答案

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

关于python - 在已编译的 Cython 代码上使用行分析器(在 ipython 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com