同时运行许多模拟

时间:2016-01-16 15:47:41

标签: python parallel-processing

我想运行许多随机沉积模拟以分析统计数据。

各个模拟并不相互依赖,但每个模拟产生一维numpy数组,我希望我的结果是由这些一维数组组成的二维数组。

我基本上对并行计算一无所知,所以我只有两个想法如何实现这个目标:

  1. 简单的for-loop,需要几天才能运行(毕竟我并不着急)
  2. 运行相同的文件很多,每个都有更短的for循环,让OS负责在运行之间分配CPU电源并在一切完成后加入文件
  3. 但是,我认为必须有更好的方法来做到这一点。我目前的代码如下:

    L = 60
    N = 100
    T = 100
    
    hrubost_relax = np.zeros((N,T))
    
    for n in range(0,N):
        level = np.zeros((T,L))
        heights = np.zeros(level.shape[1])
    
        for t in range(1,level.shape[0]):
            pos = np.random.randint(level.shape[1])
    
            left = heights[pos-1] if pos-1>0 else heights[-1]
            right = heights[pos+1] if pos+1<L else heights[0]
    
            if left<heights[pos]:
                if right<heights[pos]:
                    direction = np.random.randint(2)*2-1
                    heights[(pos+direction)%L] += 1
                else:
                    heights[pos-1] += 1
            elif right<heights[pos]:
                heights[(pos+1)%L] += 1
            else:
                heights[pos] += 1
    
            hrubost_relax[n,t] = heights.std()/L
    

    我想并行化外部for-loop

    编辑以使用multiprocessing.Pool显示我的解决方案

    from multiprocessing import Pool
    
    L = 60
    N = 1000
    T = 100000
    
    hrubost_relax = np.zeros((N,T))
    
    def deposition(n):
        level = np.zeros((T,L))
        heights = np.zeros(level.shape[1])
        w = np.zeros(T)
    
        for t in range(1,level.shape[0]):
            pos = np.random.randint(level.shape[1])
    
            left = heights[pos-1] if pos-1>0 else heights[-1]
            right = heights[pos+1] if pos+1<L else heights[0]
    
            if left<heights[pos]:
                if right<heights[pos]:
                    direction = np.random.randint(2)*2-1
                    heights[(pos+direction)%L] += 1
                else:
                    heights[pos-1] += 1
            elif right<heights[pos]:
                heights[(pos+1)%L] += 1
            else:
                heights[pos] += 1
    
            w[t] = heights.std()/L
    
        return w
    
    p = multiprocessing.Pool(4)
    for i,x in enumerate(p.map(deposition, range(N))):
        hrubost_relax[i] = x
    

1 个答案:

答案 0 :(得分:2)

如果您使用CPython实现,由于使用了全局解释器锁,线程无法为此问题提供任何加速,只允许单个线程在任何时间执行(我假设计算是CPU-界)。但是,如果您的计算机中有多个处理器,multiprocessing module 将允许您并行运行多个进程。但是,尝试运行比处理器更多的进程仍然没有实际价值,因此您应该考虑使用multiprocessing.Pool

相关问题