【发布时间】:2015-10-07 19:47:39
【问题描述】:
我编写了一个程序,它接收大型数据集作为输入(~150mb 文本文件),对它们进行一些数学运算,然后在直方图中报告结果。必须执行的计算次数与数据集中两个点的组合数量成正比,对于 100 万个点的数据集来说,这是非常大的(约 50 亿)。
我希望通过使用 Python 的 multiprocessing 模块将部分直方图数据的计算分配给各个进程,同时将最终直方图的数组保存在共享内存中,以便每个进程可以添加到它,从而减少一些计算时间.
我已经使用multiprocessing 创建了这个程序的工作版本,通常基于this answer 中描述的过程,但是我发现它实际上比我之前编写的非并行版本慢了一点。我尝试取消对共享阵列的同步访问,发现这会显着加快速度,但会导致部分数据丢失。
下面是代码的概要:
import numpy as np
from multiprocessing import Pool, Array
BINS = 200
DMAX = 3.5
DMIN = 0
def init(histo):
global histo_shared
histo_shared = histo
def to_np_array(mp_array):
return np.frombuffer(mp_array.get_obj())
# synchronize access to shared array
def calc_sync(i):
with histo_shared.get_lock():
calc_histo(i)
def calc_histo(i):
# create new array 'd_new' by doing some math on DATA using argument i
histo = to_np_array(histo_shared)
histo += np.histogram(d_new, bins=BINS,
range=(DMIN, DMAX))[0].astype(np.int32)
def main():
# read in data and calculate no. of iterations
global DATA
DATA = np.loadtxt("data.txt")
it = len(DATA) // 2
# create shared array
histo_shared = Array('l', BINS)
# write to shared array from different processes
p = Pool(initializer=init, initargs=(histo_shared,))
for i in range(1, it + 1):
p.apply_async(calc_sync, [i])
p.close()
p.join()
histo_final = to_np_array(histo_shared)
np.savetxt("histo.txt", histo_final)
if __name__ == '__main__':
main()
这里有什么我遗漏的东西会对我的表现产生严重影响吗?有什么办法可以解决这个问题以加快速度?
非常感谢任何见解或建议!
【问题讨论】:
标签: python arrays performance numpy multiprocessing