我试图在Python中运行一堆仿真,所以我尝试通过多处理来实现它。
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
import psutil
from Functions import hist, exp_fit, exponential
N = 100000 # Number of observations
tau = 13362.525 # decay rate to simulate
iterations = 1 # Number of iterations for each process
bin_size = 1*1e9 # in nanoseconds
def spawn(queue):
results = []
procs = list()
n_cpus = psutil.cpu_count()
for cpu in range(n_cpus):
affinity = [cpu]
d = dict(affinity=affinity)
p = mp.Process(target=run_child, args=[queue], kwargs=d)
p.start()
procs.append(p)
for p in procs:
results.append(queue.get)
p.join()
print('joined')
return results
def run_child(queue, affinity):
proc = psutil.Process() # get self pid
proc.cpu_affinity(affinity)
print(affinity)
np.random.seed()
for i in range(iterations):
time = np.sort(-np.log(np.random.uniform(size=N)) * tau) * 1e9
n, bins = hist(time, bin_size)
fit = exp_fit(n, bins, silent=True)
queue.put(fit)
if __name__ == '__main__':
output = mp.Queue()
plt.figure()
results = spawn(output)
bins = range(1000)
for fit in results:
plt.plot(bins, exponential(fit.params, bins), 'k-', alpha=0.1)
plt.show()
我的尝试受到this答案的极大启发,我自己尝试找到解决方案时发现,其中每个进程的亲和力都是手动设置为numpy的,这显然会更改默认行为(如果仅在单个内核上运行,这还没有完成。)
我认为该代码大部分有效;每个过程都按照预期进行仿真和拟合,但是我无法弄清楚如何提取结果。现在,run_child方法中的queue.put(fit)似乎导致程序停止。
关于这种情况为什么发生以及如何解决的任何想法?
答案 0 :(得分:1)
问题是试图将OptimizeResult数据类型传递到队列。从拟合中仅提取必要的数据,然后传递,就象魅力一样。
感谢Pierre-Nicolas Piquin帮助解决该问题!