如何在numpy bool数组上使用cython memoryview?

时间:2017-08-21 14:39:37

标签: python numpy cython

我经常使用bool数组。所以我想在cython中也这样做。但是,我无法使新的memoryview接口在numpy bool矩阵上工作。

这是我的测试:

def test_oldbuffer_uint8(np.ndarray[np.uint8_t, ndim=2] input):
    cdef size_t i, j
    cdef long total = 0
    cdef size_t J = input.shape[0]
    cdef size_t I = input.shape[1]
    for j in range(J):
        for i in range(I):
            total +=input[i, j]
    return total


def test_memview_uint8(np.uint8_t[:,:] input):
    cdef size_t i, j
    cdef long total = 0
    cdef size_t J = input.shape[0]
    cdef size_t I = input.shape[1]
    for j in range(J):
        for i in range(I):
            total +=input[i, j]
    return total


def test_oldbuffer_bool(np.ndarray[np.uint8_t, ndim=2, cast=True] input):
    cdef size_t i, j
    cdef long total = 0
    cdef size_t J = input.shape[0]
    cdef size_t I = input.shape[1]
    for j in range(J):
        for i in range(I):
            total +=input[i, j]
    return total


from cpython cimport bool
def test_memview_bool(bool[:,:] input):
    cdef size_t i, j
    cdef long total = 0
    cdef size_t J = input.shape[0]
    cdef size_t I = input.shape[1]
    for j in range(J):
        for i in range(I):
            total +=input[i, j]
    return total

然后我只是将一个随机布尔数组传递给它们:

def test_memview():
    import fuzedtest1
    a = np.random.randn(10000,10000)
    a = a>0
    sum = a.sum()
    b = a.astype(np.uint8)
    funcs = [
        (fuzedtest1.test_oldbuffer_uint8, b),
        (fuzedtest1.test_memview_uint8, b),
        (fuzedtest1.test_oldbuffer_bool, a),
        (fuzedtest1.test_memview_bool, a),

    ]
    for _func, _arr in funcs:
        try:
            _sum = _func(_arr)
            t = timeit.timeit(lambda : _func(_arr), number=10)
            print("{} time = {}, res = {} _sum = {}".format(_func, t, _sum, sum))
        except Exception as err:
            print(err)

结果如下:

<built-in function test_oldbuffer_uint8> time = 1.4905898699998943, res = 50000391 _sum = 50000391
<built-in function test_memview_uint8> time = 1.483763039999758, res = 50000391 _sum = 50000391
<built-in function test_oldbuffer_bool> time = 1.488173633999395, res = 50000391 _sum = 50000391
Does not understand character buffer dtype format string ('?')

如何在memoryview上下文中执行cast = True?

0 个答案:

没有答案