在循环中检查两个内存视图的有效方法是什么?

Mas*_*dam 6 python loops cython python-3.x typed-memory-views

我想通过使用内存视图来加速我的代码。这是我使用的两个类:

cdef class child:
    cdef public int[:] move
    def __init__(self, move):
        self.move = move

cdef class parent:
    cdef public:
        list children
        int[:, :] moves
    def __init__(self):
        self.children = []
    def add_children(self, moves):
        cdef int i = 0
        cdef int N = len(moves)
        for i in range(N):
            self.children.append(child(moves[i]))
Run Code Online (Sandbox Code Playgroud)

这是我想检查类是否有效的代码:

temp = []
for i in range(100):
    temp.append([i, i+1])

cdef int[:, :] moves = np.asarray(temp, dtype=np.int32)
a = parent()
a.add_children(moves)
for move in moves:
    for ch in a.children:
        if move == ch.move:
            print('ok')
Run Code Online (Sandbox Code Playgroud)

我希望打印 100,ok但我什么也没得到。我知道如果我使用list(move) == list(ch.move)我可以获得预期的输出,但我不希望循环中的转换开销。

谁能以有效的方式帮助我?如果有人有任何其他提高代码速度的建议,将不胜感激。

MSe*_*ert 1

您可以利用memcmpc 库中的(比较内存的函数):

from libc.string cimport memcmp

cdef int[:, :] moves = np.asarray(temp, dtype=np.int32)
cdef int[:] move
cdef child ch
a = parent()
a.add_children(moves)
for move in moves:
    for ch in a.children:
        if memcmp(&move[0], &ch.move[0], move.nbytes) == 0:
            print('ok')
Run Code Online (Sandbox Code Playgroud)

然而,如果内存视图具有不同的数据类型、字节顺序或步幅,这可能(可能)导致问题 - 因为memcmp只是比较普通内存。