如何加快对python数组的操作?

时间:2019-09-27 08:55:12

标签: python performance loops numpy

我有一个1D numpy数组A,形状为(N乘1),其中N = 4000000。我需要在每个元素上运行一个函数(fcn)。

import bumpy as np
def fcn(a, B, c):
    return a - np.sqrt(c) * B) / np.sqrt(1 - c)

由于B为(M = 100 x P = 20),而c为标量,因此该函数的输出为大小为M x P的数组。

我尝试了不同的方法,但是例如,它们都很慢:

for a in A:
    result = fcn(a, B, c)
    # do something with result...

您知道如何加快速度吗,例如通过多处理或其他任何方式?

1 个答案:

答案 0 :(得分:0)

如果您有足够的内存,@hpaulj会建议最简单的方法:

for result in (A[:,None,None] - np.sqrt(c) * B) / np.sqrt(1 - c):
    # do stuff

如果您的内存不足,请至少预先计算您可以执行的操作:

X = 1 / np.sqrt(1 - c)
Y = np.sqrt(c) * B / np.sqrt(1 - c)
for a in A:
    result = a * X - Y
    # do stuff