我在python中启动了一个项目,主要由循环组成。几天前我读到了cython,它可以帮助你通过静态输入获得更快的代码。 我开发了这两个函数来检查性能(一个在python中,另一个在cython中):
import numpy as np
from time import clock
size = 11
board = np.random.randint(2, size=(size, size))
def py_playout(board, N):
black_rave = []
white_rave = []
for i in range(N):
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))
return black_rave, white_rave
cdef cy_playout(board, int N):
cdef list white_rave = [], black_rave = []
cdef int M = board.shape[0], L = board.shape[1]
cdef int i=0, x=0, y=0
for i in range(N):
for x in range(M):
for y in range(L):
if board[(x,y)] == 0:
black_rave.append((x,y))
else:
white_rave.append((x,y))
return black_rave, white_rave
我使用下面的代码来测试性能:
t1 = clock()
a = playout(board, 1000)
t2 = clock()
b = playout1(board, 1000)
t3 = clock()
py = t2 - t1
cy = t3 - t2
print('cy is %a times better than py'% str(py / cy))
但是我没有发现任何明显的改进。我还没有使用过Typed-Memoryviews。任何人都可以提出有用的解决方案来提高速度或帮助我使用typed-memoryview重写代码吗?
答案 0 :(得分:4)
你是对的,没有在cython函数中为board
参数添加类型,加速并不是那么多:
%timeit py_playout(board, 1000)
# 321 ms ± 19.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit cy_playout(board, 1000)
# 186 ms ± 541 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
但它仍然是两个更快的因素。通过添加类型,例如
cdef cy_playout(int[:, :] board, int N):
# ...
# or if you want explicit types:
# cimport numpy as np
# cdef cy_playout(np.int64_t[:, :] board, int N): # or np.int32_t
它更快(几乎快10倍):
%timeit cy_playout(board, 1000)
# 38.7 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
我还使用timeit
(好的IPython魔法%timeit
)来获得更准确的时间。
请注意,您还可以使用numba来实现极佳的加速,而无需任何额外的静态输入:
import numba as nb
nb_playout = nb.njit(py_playout) # Just decorated your python function
%timeit nb_playout(board, 1000)
# 37.5 ms ± 154 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
答案 1 :(得分:0)
我实现了一个运行得更快的功能。我只是将black_rave
和white_rave
声明为内存视图,并将它们放在返回值中:
cdef tuple cy_playout1(int[:, :] board, int N):
cell_size = int((size ** 2) / 2) + 10
cdef int[:, :] black_rave = np.empty([cell_size, 2], dtype=np.int32)
cdef int[:, :] white_rave = np.empty([cell_size, 2], dtype=np.int32)
cdef int i, j, x, y, h
i, j = 0, 0
cdef int M,L
M = board.shape[0]
L = board.shape[1]
for h in range(N):
for x in range(M):
for y in range(L):
if board[x,y] == 0:
black_rave[i][0], black_rave[i][1] = x, y
i += 1
elif board[x,y] == 1:
white_rave[j][0], white_rave[j][1] = x, y
j += 1
i = 0
j = 0
return black_rave[:i], white_rave[:j]
这是速度测试结果:
%timeit py_playout(board, 1000)
%timeit cy_playout(board, 1000)
%timeit cy_playout1(board, 1000)
# 1 loop, best of 3: 200 ms per loop
# 100 loops, best of 3: 9.26 ms per loop
# 100 loops, best of 3: 4.88 ms per loop