如何在 Python 中进行并行编程?

新手上路,请多包涵

对于C++,我们可以使用OpenMP进行并行编程;但是,OpenMP 不适用于 Python。如果我想并行我的 python 程序的某些部分,我该怎么办?

代码的结构可以认为是:

 solve1(A)
solve2(B)

其中 solve1solve2 是两个独立的函数。如何并行运行这种代码而不是顺序运行以减少运行时间?代码是:

 def solve(Q, G, n):
    i = 0
    tol = 10 ** -4

    while i < 1000:
        inneropt, partition, x = setinner(Q, G, n)
        outeropt = setouter(Q, G, n)

        if (outeropt - inneropt) / (1 + abs(outeropt) + abs(inneropt)) < tol:
            break

        node1 = partition[0]
        node2 = partition[1]

        G = updateGraph(G, node1, node2)

        if i == 999:
            print "Maximum iteration reaches"
    print inneropt

其中 setinnersetouter 是两个独立的函数。那就是我想并行的地方……

原文由 ilovecp3 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 542
2 个回答

您可以使用 多处理 模块。对于这种情况,我可能会使用处理池:

 from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

这将产生可以为您完成通用工作的进程。由于我们没有通过 processes ,它将为您机器上的每个 CPU 核心生成一个进程。每个 CPU 内核可以同时执行一个进程。

如果您想将列表映射到单个函数,您可以这样做:

 args = [A, B]
results = pool.map(solve1, args)

不要使用线程,因为 GIL 会锁定对 python 对象的任何操作。

原文由 Matt Williamson 发布,翻译遵循 CC BY-SA 3.0 许可协议

这可以用 Ray 非常优雅地完成。

要并行化您的示例,您需要使用 @ray.remote 装饰器定义函数,然后使用 .remote 调用它们。

 import ray

ray.init()

# Define the functions.

@ray.remote
def solve1(a):
    return 1

@ray.remote
def solve2(b):
    return 2

# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)

# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])

多处理 模块相比,它有许多优点。

  1. 相同的代码将在多核机器和机器集群上运行。
  2. 进程通过 共享内存和零拷贝序列化 有效地共享数据。
  3. 错误消息传播得很好。
  4. 这些函数调用可以组合在一起,例如,
    @ray.remote
   def f(x):
       return x + 1

   x_id = f.remote(1)
   y_id = f.remote(x_id)
   z_id = f.remote(y_id)
   ray.get(z_id)  # returns 4

  1. 除了远程调用函数之外,类还可以被远程实例化为 actors

请注意, Ray 是我一直在帮助开发的一个框架。

原文由 Robert Nishihara 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏