如何确保在 python 多处理中使用所有处理器?

How to ensure all processors are utilized in python multiprocessing?

我是多处理概念的新手。

我的代码

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 被哪个进程使用了​​

你的例子中有几处不对劲。

  • 您只启动一个子进程,负责处理所有数字。
  • 您缺少 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()现在只处理一个号码。应该是真的return它来打印加工,而不是自己打印,不过这是一个简单的例子。
  • 您可以在 Pool 上使用 .map().imap() 或其他一些方法;我选择 .imap_unordered() 是因为我不关心获取这些值的顺序(此外,我对它们什么也不做)。

没什么特别的 "locks" 单个进程到单个 CPU,但是 – 毕竟,单个进程可能会利用多个线程,OS 调度程序可能会安排到多个线程上不同的 CPU。不过,不同的 OSes 有 API 来限制每个进程(和线程)的处理器;如果你真的需要,你可以深入研究。