简体   繁体   English

Python 多处理产生不稳定的结果

[英]Python multiprocessing producing unstable results

Can anyone help me understand why this simple example of trying to speed up a for loop using python's multiprocessing module produces unstable results?谁能帮我理解为什么这个尝试使用python的multiprocessing模块加速for循环的简单示例会产生不稳定的结果? I use a Manager.List to store the values from the child processes.我使用Manager.List来存储来自子进程的值。

Clearly I'm doing at least one thing wrong.显然,我至少做错了一件事。 What would be the correct way to do this?这样做的正确方法是什么?

import numpy as np
import multiprocessing
from matplotlib import pyplot as plt

from functools import partial
from multiprocessing import Manager


def run_parallel(x_val, result):

    val = np.arctan(x_val)

    result.append(val)


def my_func(x_array, parallel=False):

    if not parallel:
        result = []
        for k in x_array:
            result.append(np.arctan(k))

        return result

    else:
        manager = Manager()
        m_result = manager.list()

        pool = multiprocessing.Pool(4)
        pool.map(partial(run_parallel, result=m_result), x_array)

        return list(m_result)


test_x = np.linspace(0.1,1,50)
serial = my_func(test_x,parallel=False)
parallel = my_func(test_x,parallel=True)

plt.figure()
plt.plot(test_x, serial, label='serial')
plt.plot(test_x,parallel, label='parallel')
plt.legend(loc='best')
plt.show()

The output I'm getting looks like this我得到的 output 看起来像这样

这个

and it looks different every time this runs.每次运行时它看起来都不一样。

I added some print functions and it turned out that the order of elements from x_array is arbitrary... That's why it looks so weird.我添加了一些打印函数,结果发现 x_array 中元素的顺序是任意的……这就是它看起来如此奇怪的原因。 I think you should keep argument and value of arctan pairs and then order it by argument value我认为您应该保留arctan对的参数和值,然后按参数值对其进行排序

EDIT编辑

I read more and it turned out that map returns values in order... This works as you wanted:我读了更多,结果发现map按顺序返回值...这可以按您的意愿工作:

import numpy as np
import multiprocessing
from matplotlib import pyplot as plt

from functools import partial
from multiprocessing import Manager


def run_parallel(x_val, result):

    val = np.arctan(x_val)
    return val


def my_func(x_array, parallel=False):
    if not parallel:
        result = []
        for k in x_array:
            result.append(np.arctan(k))

        return result

    else:
        manager = Manager()
        m_result = manager.list()

        pool = multiprocessing.Pool(4)
        x = pool.map(partial(run_parallel, result=m_result), x_array)
        return list(x)


test_x = np.linspace(0.1,1,50)
parallel = my_func(test_x,parallel=True)

plt.figure()
plt.plot(test_x,parallel, label='parallel')
plt.legend(loc='best')
plt.show()

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

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