简体   繁体   English

Python 多处理:提取结果

[英]Python multiprocessing: Extracting results

I'm trying to run a bunch of simulations in Python, so I tried implementing it with multiprocessing.我试图在 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()

My attempt is heavily inspired by this answer I found while trying to find a solution myself, where the affinity of each process is manually set as numpy apparently changes the default behaviour (it only runs on a single core if this is not done).我的尝试深受我自己在尝试找到解决方案时发现的这个答案的启发,其中每个进程的亲和性被手动设置为 numpy 显然会改变默认行为(如果不这样做,它只会在单个核心上运行)。

I think the code mostly works;我认为代码大多有效; each process performs a simulation and fit as intended, but I cannot figure out how to extract the results.每个过程都按预期执行模拟和拟合,但我无法弄清楚如何提取结果。 As it is now, the queue.put(fit) in the run_child method seems to cause the program to halt.现在,run_child 方法中的 queue.put(fit) 似乎导致程序停止。

Any ideas as to why this happens, and how to fix it?关于为什么会发生这种情况以及如何解决它的任何想法?

The problem was trying to pass an OptimizeResult data type to the queue.问题是试图将 OptimizeResult 数据类型传递给队列。 Extracting only the necessary data from the fit and passing that instead worked like a charm.仅从拟合和传递中提取必要的数据,这反而像魅力一样工作。

Thanks to Pierre-Nicolas Piquin for helping solve it!感谢 Pierre-Nicolas Piquin 帮助解决它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM