Jupyter notebook 在jupyter笔记本中使用cython进行线条分析
我正在尝试使用jupyter笔记本中带有cython函数的liner_profiler库。它只起了一半作用。我得到的结果只包括函数的第一行,没有分析结果Jupyter notebook 在jupyter笔记本中使用cython进行线条分析,jupyter-notebook,cython,line-profiler,Jupyter Notebook,Cython,Line Profiler,我正在尝试使用jupyter笔记本中带有cython函数的liner_profiler库。它只起了一半作用。我得到的结果只包括函数的第一行,没有分析结果 %%cython -a # cython: linetrace=True # cython: binding=True # distutils: define_macros=CYTHON_TRACE_NOGIL=1 import numpy as np cimport numpy as np from datetime import datet
%%cython -a
# cython: linetrace=True
# cython: binding=True
# distutils: define_macros=CYTHON_TRACE_NOGIL=1
import numpy as np
cimport numpy as np
from datetime import datetime
import math
cpdef np.int64_t get_days(np.int64_t year, np.int64_t month):
cdef np.ndarray months=np.array([31,28,31,30,31,30,31,31,30,31,30,31])
if month==2:
if (year%4==0 and year%100!=0) or (year%400==0):
return 29
return months[month-1]
对于分析结果int onlt显示一行代码
Timer unit: 1e-07 s
Total time: 0.0015096 s
File: .ipython\cython\_cython_magic_0154a9feed9bbd6e4f23e57d73acf50f.pyx
Function: get_days at line 15
Line # Hits Time Per Hit % Time Line Contents
==============================================================
15 cpdef np.int64_t get_days(np.int64_t year, np.int64_t month):
如果line_profiler应该支持Cython,那么它可以被看作是line_profiler中的一个bug。要获取已分析函数的代码,请使用line_profiler并在inspect.getblock的帮助下尝试提取代码: ... 读取pyx文件 所有\u行=linecache.getlinesfilename 尝试在开始处提取函数体字符串。\u line否: 子行=检查。getblockall\u行[开始\u行编号-1:] ... 然而,getblock对cpdef函数一无所知,因为python只有def函数,因此产生了错误的函数体,即只有签名 解决方法: 一个简单的解决方法是引入一个伪def函数,它是cpdef函数的哨兵,其方式是inspect.getblock将产生cpdef函数的整个主体+哨兵函数的主体,即: %%赛昂 ... cpdef np.int64获取日np.int64获取年,np.int64获取月: ... def get_days_sentinel: 通过 现在报告%lprun-f get_days get_days 2019,3如下所示:
Timer unit: 1e-06 s
Total time: 1.7e-05 s
File: XXXX.pyx
Function: get_days at line 10
Line # Hits Time Per Hit % Time Line Contents
==============================================================
10 cpdef np.int64_t get_days(np.int64_t year, np.int64_t month):
11 1 14.0 14.0 82.4 cdef np.ndarray months=np.array([31,28,31,30,31,30,31,31,30,31,30,31])
12 1 1.0 1.0 5.9 if month==2:
13 if (year%4==0 and year%100!=0) or (year%400==0):
14 return 29
15 1 2.0 2.0 11.8 return months[month-1]
16
17 def get_days_sentinel():
18 pass
哨兵仍然有一些丑陋的尾随线,但最好不要看到任何东西。你真的调用了这个函数吗?看起来您唯一要做的就是定义函数,因此只有cpdef行运行是的,我在下一个单元格中调用它:%lprun-f get_days get_days 2019,3line profiler似乎与cdef函数或cpdef有问题。不确定这是Cython的问题还是line_profiler的问题。这也将作为问题进行跟踪。