我想运行许多随机沉积模拟,以便分析统计数据。你知道吗
单独的模拟并不相互依赖,但是每个模拟产生一个1-D numpy数组,我希望我的结果是由这些1-D数组组成的一个2-D数组。你知道吗
我基本上对并行计算一无所知,所以我只有两个想法来实现这一点:
然而,我认为必须有更好的方法来做到这一点。我当前的代码如下:
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循环并行化
编辑以显示我的解决方案多处理池
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
如果您使用的是CPython实现,由于它使用了一个全局解释器锁,线程不能在这个问题上给您任何加速,这个锁只允许单个线程在任何时候执行(我假设计算是CPU限制的)。但是,如果您的计算机中有多个处理器,^{} module
将允许您并行运行多个进程。但是,尝试运行比处理器更多的进程仍然没有实际价值,因此应该考虑使用^{}
相关问题 更多 >
编程相关推荐