Python multiprocessing: Extracting results

╄→гoц情女王★ 提交于 2021-01-28 11:10:47

问题


I'm trying to run a bunch of simulations in Python, so I tried implementing it with multiprocessing.

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).

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.

Any ideas as to why this happens, and how to fix it?


回答1:


The problem was trying to pass an OptimizeResult data type to the queue. 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!



来源:https://stackoverflow.com/questions/54724446/python-multiprocessing-extracting-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!