【发布时间】:2015-10-16 17:56:17
【问题描述】:
我想提高这个函数中for循环的性能。
import numpy as np
import random
def play_game(row, n=1000000):
"""Play the game! This game is a kind of random walk.
Arguments:
row (int[]): row index to use in the p matrix for each step in the
walk. Then length of this array is the same as n.
n (int): number of steps in the random walk
"""
p = np.array([[ 0.499, 0.499, 0.499],
[ 0.099, 0.749, 0.749]])
X0 = 100
Y0 = X0 % 3
X = np.zeros(n)
tempX = X0
Y = Y0
for j in range(n):
tempX = X[j] = tempX + 2 * (random.random() < p.item(row.item(j), Y)) - 1
Y = tempX % 3
return np.r_[X0, X]
难点在于Y的值在每一步都是根据X的值计算出来的和Y然后在下一步更新X 的值。
我想知道是否有一些 numpy 技巧可以产生很大的不同。使用 Numba 是公平的游戏(我尝试过,但没有多大成功)。但是,我不想使用 Cython。
【问题讨论】:
-
如果您使用的是 Python2,使用
xrange()而不是range()可能会有所帮助。 -
我正在使用 Python 3。
标签: python performance numpy vectorization numba