【问题标题】:For-loop with multiprocessing in PythonPython中具有多处理的for循环
【发布时间】:2018-06-15 01:44:00
【问题描述】:

这里是创建图并满足一定条件的代码sn-p的结构:

for i in range(1, len(binary_combinations)):

    # ...something          

    h=0
    while len(added)<i+1:   

         #...something  

         for j in it.combinations(good, 8):

             #...something

         h=h+1

binary_combinationsaddedgood 是一些列表。 我正在尝试为整个 for 循环实现多处理。或仅用于函数it.combinations,但无济于事,因为我无法将其与while循环的执行相协调。 如何处理?

【问题讨论】:

  • 在多处理之前,您是否考虑过对代码进行矢量化处理?
  • 我没有考虑它,因为我还不太擅长矢量化。但如果有帮助,我将不得不阅读更多相关信息:)
  • 其次,我对'普通'循环感兴趣,因为列表中的值很多,以免在操作内存中记住完整的结果。
  • 你能提供一个可重现的例子吗?
  • 是一个完整代码的例子ufile.io/1v419

标签: python python-3.x for-loop while-loop multiprocessing


【解决方案1】:

可以看出,你可以很容易地抽象出第一个 for 循环:

from multiprocessing import Pool, cpu_count
import itertools as it

def foo(i):
    global added
    global good
    h=0
    while len(added)<i+1:   
        #...something  
        for j in it.combinations(good, 8):
            #...something
            h=h+1

pool = Pool(cpu_count())
results = pool.map(foo, range())

您将遇到的主要问题是,如果您要更改 #...something 代码块中的列表,那将毫无价值,因为进程不会共享它们的堆栈状态。

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 2020-09-25
    • 2022-12-04
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多