【问题标题】:How to ensure all processors are utilized in python multiprocessing?如何确保在 python 多处理中使用所有处理器?
【发布时间】:2019-02-12 18:20:24
【问题描述】:

我是多处理概念的新手。

我的代码

from multiprocessing import Process
def square(x):
 
    for x in numbers:
        print('%s squared  is  %s' % (x, x**2))
 
if __name__ == '__main__':
    numbers = [43, 50, 5, 98, 34, 35]
 
    p = Process(target=square, args=('x',))
    p.start()
    p.join
    print "Done"
     

结果

Done
43 squared  is  1849
50 squared  is  2500
5 squared  is  25
98 squared  is  9604
34 squared  is  1156
35 squared  is  1225

我明白了,我们可以使用multiprocessing.cpu_count()来获取系统中的cpu数量

但是,我未能实现 2 件感兴趣的事情。 -

  1. 在所有 cpu 中平均分配所有任务
  2. 检查哪个 CPU 被哪个进程使用了​​

【问题讨论】:

  • @AKX 非常成功,所以这里只是一个指向您目前似乎错过的相关docs 的链接。因为Pool 中的工作分配取决于对要处理的迭代进行分块,here 您可以找到有关该方面的一些背景。

标签: python parallel-processing multiprocessing python-multiprocessing


【解决方案1】:

您的示例中有几处有问题。

  • 您只需启动一个子进程,该子进程负责处理所有数字。
  • 您缺少 p.join() 中的括号,因此从不等待该过程(这就是首先打印 Done 的原因)。

您应该改用multiprocessing.Pool,类似这样。

from multiprocessing import Pool

def square(x):
    print('%s squared is %s' % (x, x**2))


if __name__ == '__main__':
    numbers = range(1, 1000, 50)

    with Pool() as p:
        for value in p.imap_unordered(square, numbers):
            # You could do something with the 
            # return value from `square` here.
            pass  

    print("Done")

这个输出(例如——不保证顺序)

1 squared is 1
51 squared is 2601
101 squared is 10201
151 squared is 22801
201 squared is 40401
251 squared is 63001
401 squared is 160801
451 squared is 203401
501 squared is 251001
301 squared is 90601
551 squared is 303601
601 squared is 361201
351 squared is 123201
651 squared is 423801
701 squared is 491401
751 squared is 564001
801 squared is 641601
851 squared is 724201
901 squared is 811801
951 squared is 904401
Done
  • Pool() 默认使用cpu_count 进程,因此您无需担心。
  • square() 现在只处理一个号码。它真的应该返回它进行打印和处理,而不是自己打印,但这是一个简单的例子。
  • 您可以在Pool 上使用.map().imap() 或其他一些方法;我选择了.imap_unordered(),因为我不关心获得这些值的顺序(此外,无论如何我对它们什么都不做)。

不过,没有什么特别会将单个进程“锁定”到单个 CPU 上——毕竟,单个进程可能会使用多个线程,操作系统调度程序可能会将这些线程调度到不同的 CPU 上。但是,不同的操作系统具有 API 来限制每个进程(和线程)的处理器;如果你真的需要,你可以深入研究这些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多