3

我正在尝试在带有 cython 功能的 jupyter 笔记本中使用 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 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):
4

1 回答 1

5

这可以看作是一个错误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:])
...

但是,对 -functiongetblock一无所知cpdef,因为 python 只有def-functions,因此会产生错误的函数体(即只有签名)。

解决方法:

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

%%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

哨兵的尾随线仍然有些难看,但最好什么都没看到。

于 2019-08-21T22:31:22.047 回答