代码之家  ›  专栏  ›  技术社区  ›  cel

将numpy数组的切片视图传递给cython-复制发生在哪里?

  •  0
  • cel  · 技术社区  · 7 年前

    在下面的代码中,我将对数组X进行切片,从而在X上创建一个名为 X_cut 然后我在切片上使用cython内存视图,并将其作为1d数组传递给一个c函数,该函数线性访问内存。

    我能确定传递给C代码的指针实际上是指6x6线性化矩阵吗?

    如果是,复制操作在哪里进行?它在里面吗 X_cut.ravel() ?

    %%cython
    
    import numpy as np
    
    cdef extern from "/some/path/to/get_5_5.c":
        long get5_5(long* arr, int M, int N)
    
    M = 6
    N = 8
    
    X = np.arange(M*N).reshape(M, N)
    
    N_cut = 6
    X_cut = X[:, :N_cut]
    
    cdef long[::1] arr = X_cut.ravel()
    
    print(get5_5(&arr[0], M, N_cut))
    

    /一些/路径/去/得到。C

    long get5_5(long* arr, int M, int N) {
      return arr[5*N + 5];
    }
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   ead    7 年前

    Cython的类型化内存视图使用 Buffer-Protocol 为了获取数据,这意味着他们与数据的复制无关。

    理论上,导出器可以在通过缓冲协议公开数据时决定复制数据。然而,通常使用缓冲协议来避免内存复制,所以复制不是正常情况。这意味着,在将类型化内存视图绑定到导出缓冲区的对象时,您不能100%确定没有复制发生——您必须知道导出器的实现,但复制的情况非常罕见。这不是这里发生的事情。

    复制必须在 X_cut.ravel() 被称为 resulting memory must be contiguous ,但是 X_cut 不是吗 X_cut.flags ),因为它仍然与 X 每行最后一个元素的删除会导致内存中出现“洞”。

    以下是内存布局(为了简单起见,M=2,N=3,N_-cut=2):

      X:               X00,X01,X02,X10,X11,X12
      X_cut:           X00,X01,...,X10,X11        # ... - hole in memory, no copying
      X_cut.ravel():   X00,X01,X10,X11            # memory contiguous, copying needed
    

    它留给你的是什么?您要么接受内存的复制,要么扩展 get5_5 ,因此您还可以传递非连续内存布局,而不是与缓冲协议不相似。

    例如通过 X_切 在不复制的情况下,您不仅需要指定形状,还需要指定沿尺寸标注的步幅,即。

    #only stride along the the first dimension is needed:
    cdef long get5_5(long* arr, int stride_row, int stride_col):
         return arr[stride_row*5+5]
    

    问题是,如何获得指针 long* arr 从…起 X_切 没有复制。

    一种可能性是使用2D内存视图(我会选择此选项):

    cdef long[:,::1] arr = X_cut
    get5_5(&arr[0][0], M, N) # and not M, N_cut
    

    另一种方法是使用 np.reshape(-1) ,它会创建一个新的一维视图,但不会 总是 复制数据(不像 np.ravel() ):

    cdef long[::1] arr = X.reshape(-1) # X_cut.reshape(-1) would copy the data!
    get5_5(&arr[0], M, N)  # and not M, N_cut
    
    推荐文章