我正在尝试通过使用 cython 功能来提高我的 python 代码的速度。我的python代码由类和py_child
函数组成,如下所示:py_parent
py_backup
import random
from time import clock
import numpy as np
from libc.string cimport memcmp
## python code #################################################
class py_child:
def __init__(self, move):
self.move = move
self.Q = 0
self.N = 0
class py_parent:
def __init__(self):
self.children = []
def add_children(self, moves):
for move in moves:
self.children.append(py_child(move))
def py_backup(parent, white_rave, black_rave):
for point in white_rave:
for ch in parent.children:
if ch.move == point:
ch.Q += 1
ch.N += 1
for point in black_rave:
for ch in parent.children:
if ch.move == point:
ch.Q += 1
ch.N += 1
这与cython
使用 memoryviews 作为一些变量的实现相同:
## cython ######################################################
cdef class cy_child:
cdef public:
int[:] move
int Q
int N
def __init__(self, move):
self.move = move
self.Q = 0
self.N = 0
cdef class cy_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(cy_child(moves[i]))
cpdef cy_backup(cy_parent parent_node, int[:, :] white_rave,int[:, :] black_rave):
cdef int[:] move
cdef cy_child ch
for move in white_rave:
for ch in parent_node.children:
if memcmp(&move[0], &ch.move[0], move.nbytes) == 0:
ch.Q += 1
ch.N += 1
for move in black_rave:
for ch in parent_node.children:
if memcmp(&move[0], &ch.move[0], move.nbytes) == 0:
ch.Q += 1
ch.N += 1
现在我想评估函数 cy_backup、py_backup 的代码速度。所以我使用以下代码:
### Setup variables #########################################
size = 11
board = np.random.randint(2, size=(size, size), dtype=np.int32)
for x in range(board.shape[0]):
for y in range(board.shape[1]):
if board[x,y] == 0:
black_rave.append((x,y))
else:
white_rave.append((x,y))
py_temp = []
for i in range(size):
for j in range(size):
py_temp.append((i,j))
#### python arguments #######################################
py = py_parent()
py.add_children(py_temp)
# also py_temp, black_rave, white_rave
#### cython arguments #######################################
cy_temp = np.assarray(py_temp, , dtype= np.int32)
cy_black_rave = np.asarray(black_rave, dtype= np.int32)
cy_white_rave = np.asarray(white_rave, dtype= np.int32)
cy = cy_parent()
cy.add_children(cy_temp)
#### Speed test #################################################
%timeit py_backup(py_parent, black_rave, white_rave)
%timeit cy_backup(cy_parent, cy_black_rave, cy_white_rave)
当我运行程序时,我对结果感到惊讶:
1000 loops, best of 3: 759 µs per loop
100 loops, best of 3: 6.38 ms per loop
我期待 cython 比 python 快得多,特别是在使用 memoryviews 时。
为什么 cython 中的循环运行速度比 python 中的循环慢?
如果有人对加速 cython 中的代码有任何建议,我们将不胜感激。
提前我为我的问题道歉,包括太多的代码。