我已经开始在 cython 中使用 memoryviews 来访问 numpy 数组。它们具有的各种优势之一是它们比旧的 numpy 缓冲区支持快得多: http: //docs.cython.org/src/userguide/memoryviews.html#comparison-to-the-old-buffer-support
但是,我有一个例子,旧的 numpy 缓冲区支持比 memoryviews 更快!怎么会这样?!我想知道我是否正确使用了内存视图?
这是我的测试:
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef np.ndarray[np.uint8_t, ndim=2] image_box1(np.ndarray[np.uint8_t, ndim=2] im,
np.ndarray[np.float64_t, ndim=1] pd,
int box_half_size):
cdef unsigned int p0 = <int>(pd[0] + 0.5)
cdef unsigned int p1 = <int>(pd[1] + 0.5)
cdef unsigned int top = p1 - box_half_size
cdef unsigned int left = p0 - box_half_size
cdef unsigned int bottom = p1 + box_half_size
cdef unsigned int right = p0 + box_half_size
cdef np.ndarray[np.uint8_t, ndim=2] box = im[top:bottom, left:right]
return box
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef np.uint8_t[:, ::1] image_box2(np.uint8_t[:, ::1] im,
np.float64_t[:] pd,
int box_half_size):
cdef unsigned int p0 = <int>(pd[0] + 0.5)
cdef unsigned int p1 = <int>(pd[1] + 0.5)
cdef unsigned int top = p1 - box_half_size
cdef unsigned int left = p0 - box_half_size
cdef unsigned int bottom = p1 + box_half_size
cdef unsigned int right = p0 + box_half_size
cdef np.uint8_t[:, ::1] box = im[top:bottom, left:right]
return box
计时结果如下:
image_box1:键入 numpy:100000 个循环,最好的 3 个:每个循环 11.2 us
image_box2:memoryview:100000 个循环,最好的 3 个:每个循环 18.1 us
这些测量是从 IPython 使用 %timeit image_box1(im, pd, box_half_size) 完成的