【问题标题】:Using multiprocessing to in a function with multiple return in simulation在具有多个返回的函数中使用多处理来模拟
【发布时间】:2022-01-05 16:56:51
【问题描述】:

我想同时使用不同的随机种子运行模拟。运行模拟的顺序代码是:

def run_multiple_simulations(n=10,T=T,p=p):
    A,B,C,D,E=[],[],[],[],[]
    for i in range(n):
        a,b,c,d,e= do_simulation(T,p=p,seed=i)
        A.append([a])
        B.append([b])
        C.append([c])
        D.append([d])
        E.append([e])
    return A,B,C,D,E

有没有办法像run_multiple_simulations() 的返回语句那样得到结果(a,b,c,d 和 e 是数组)。

【问题讨论】:

  • 请添加最低可运行代码和您的预期结果。
  • 是的,这是可能的。签出 joblib 或 multiprocessing 模块,但为了帮助您,我们将需要一个最小的代码示例来重现该行为!只为一个模拟编写一个片段,给它一个 id 值并将其放入多处理中!

标签: python multithreading multiprocessing return


【解决方案1】:

你可以使用ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def do_simulation(t, p, seed):  # (1)
    return (1, 2, 3, 4, 5)

def run_multiple_simulations(n, t, p):
    def _do_simulation(seed):  # (2)
        return do_simulation(t, p, seed)

    with ThreadPoolExecutor() as e:
        results = e.map(_do_simulation, range(n))  # (3)

    return tuple(zip(*results))  # (4)

print(run_multiple_simulations(3, 0, 0))

我在 (1) 中定义了您的函数的模拟版本。函数 (2) 是 (1) 的柯里化版本,只有种子参数,因为它是执行之间唯一变化的参数。然后,ThreadPoolExecutor 用于并行执行工作 (3)。最后(4),结果按照你想要的格式(列表元组)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2011-05-26
    • 2014-03-22
    • 1970-01-01
    • 2014-06-23
    • 2015-08-25
    • 2014-04-10
    相关资源
    最近更新 更多