我正在尝试使用 python 处理来自多个数据站的一些大型数据集。我的想法是使用 multiprocessing.pool 为每个 CPU 分配来自单个站的数据,因为来自每个站的数据彼此独立。
但是,与单个 for 循环相比,我的计算时间似乎并没有真正减少。
这是我的部分代码:
#function calculating the square of each data point, and taking the cumulative sum
def get_cumdd(data):
#if not isinstance(data, list):
# data = [data]
dd = np.zeros((len(data),1))
cum_dd = np.zeros((len(data),1))
for i in range(len(data)):
dd[i] = data[i]**2
cum_dd=np.cumsum(dd)
return cum_dd
#parallelization between each station
if __name__ == '__main__':
n_proc = np.min([mp.cpu_count(),nstation]) #nstation = 10
p = mp.Pool(processes=int(n_proc))
result = p.map(get_cumdd,data)
p.close()
p.join()
cum_dd = np.zeros((nstation,len(data[0])))
for i in range(nstation):
cum_dd[i] = result[i].T
我不使用 chunksize,因为 cum_dd 对所有之前的数据求和^2。我基本上将我的数据分成 10 个相等的部分,因为进程之间没有通信。我想知道我是否在这里遗漏了什么。
我的数据每站每天200万个点,需要处理多年的数据。
请您参考如下方法:
这并没有直接解决您的多处理问题,但是(正如 Ugur MULUK 和 Iguananaut 提到的)我认为您的 get_cumdd 函数效率低下。 Numpy 提供 np.cumsum .重新实现你的函数,我得到了超过 1000 倍的 10k 元素数组加速。使用 100k 个元素,它的速度大约快 7000 倍。对于 2M 个元素,我懒得让它完成。
# your function
def cum_dd(data):
#if not isinstance(data, list):
# data = [data]
dd = np.zeros((len(data),1))
cum_dd = np.zeros((len(data),1))
for i in range(len(data)):
dd[i] = data[i]**2
cum_dd[i]=np.sum(dd[0:i])
return cum_dd
# numpy implementation
def cum_dd2(data):
# adding an axis to match the shape of the output of your cum_dd function
return np.cumsum(data**2)[:, np.newaxis]
对于 2e6 点,此实现在我的计算机上需要大约 11 毫秒。我认为单个站点 10 年的数据大约需要 30 秒。
