在Jupyter Notebook中使用cython进行行轮廓分析

亚历克斯·T

我正在尝试在具有cython功能的jupyter笔记本中使用衬里档案库。它只在中途工作。我得到的结果仅包含函数的第一行,而没有分析结果。

%%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):
ad

可以将其视为中的错误line_profiler(如果应该支持Cython)。要获取配置文件函数的代码,请line_profiler 读取pyx-file并尝试在以下帮助下提取代码inspect.getblock

...
# read pyx-file
all_lines = linecache.getlines(filename)
# try to extract body of the function strarting at start_lineno:
sublines = inspect.getblock(all_lines[start_lineno-1:])
...

但是,getblockcpdef-function一无所知,因为python仅具有def-functions,因此产生错误的function-body(即仅签名)。

解决方法:

一个简单的解决方法是引入一个伪def函数cpdef-以这种方式inspect.getblock将其作为-函数的哨兵从而产生cpdef-function的整体+哨兵函数的主体,即:

%%cython
...
cpdef np.int64_t get_days(np.int64_t year, np.int64_t month):
    ...

def get_days_sentinel():
    pass

现在该报告%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

从前哨仍然有一些难看的尾随线,但最好是根本不看任何东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章