遍历数组时Cupy比numpy慢

时间:2019-08-07 02:49:58

标签: cupy

我有想要与cupy并行化的代码。我认为这很简单-只需写“ import cupy as cp”,然后将我写的np。替换为cp,就可以了。

而且,它确实可以运行,代码可以运行,但是速度慢得多。我认为,与numpy相比,通过较大的数组进行迭代最终会更快,但似乎从未发生。

代码是:

q = np.zeros((5,5))
q[:,0] = 20

def foo(array):

    result = array
    shedding_row = array*0
    for i in range((array.shape[0])):
        for j in range((array.shape[1])-1):

            shedding_param = 2 * (result[i,j])**.5             
            shedding = (np.random.poisson( (shedding_param), 1))[0]

            if shedding >= result[i,j]:
                shedding = result[i,j] - 1

            result[i,j+1] = result[i,j] - shedding

            if result[i,j+1]<0:
                result[i,j+1] = 0

            shedding_row[i,j+1] = shedding  

    return(result,shedding_row)

x,y = foo(q)

这应该使cupy变得更快吗?我用错了吗?

1 个答案:

答案 0 :(得分:2)

要获得numpycupy的快速性能,应使用并行操作而不是for循环。

例如,

for i in range((array.shape[0])):
    for j in range((array.shape[1])-1):

        shedding_param = 2 * (result[i,j])**.5

这可以计算为

xp = numpy  # change to cupy for GPU
shedding_param = 2 * xp.sqrt(result[:, :-1])