Cython:在不与 python 交互的情况下索引类属性的类型化内存视图

问题描述 投票:0回答:1

我有一个代码,例如

import numpy as np

cdef class A:
    cdef float[:] x

    def __init__(self):
        self.x = np.arange(10)

    @cython.boundscheck(False)  # turn off bounds-checking for entire function
    @cython.wraparound(False)
    @cython.cdivision(True)     # turn off checking for division by zero
    def func(self):
        cdef Py_ssize_t i

        for i in range(10):
            self.x[i]

enter image description here

我希望索引

self.x[i]
完全用C完成,但它一直与python交互,我不知道为什么。如果我像下面这样更改代码,

import numpy as np

cdef class A:
    cdef float[:] x

    def __init__(self):
        self.x = np.arange(10)

    @cython.boundscheck(False)  # turn off bounds-checking for entire function
    @cython.wraparound(False)
    @cython.cdivision(True)     # turn off checking for division by zero
    def func(self):
        cdef Py_ssize_t i
        cdef float[:] x

        x = self.x
        for i in range(10):
            x[i]

enter image description here

然后索引

x[i]
不与Python交互。如何在不与 python 交互的情况下直接索引
self.x

python indexing cython class-attributes typed-memory-views
1个回答
0
投票

您想要指令

@cython.initializedcheck(False)

跳过检查。

当然,你需要确定你已经初始化了它,所以不要不假思索地将检查复制粘贴到各处。 (这也适用于

boundcheck
wraparound
cdivision
)。

© www.soinside.com 2019 - 2024. All rights reserved.