5

我是一个多处理新手,

我对线程有所了解,但我需要提高这种计算的速度,希望通过多处理:

示例描述:将字符串发送到线程,更改字符串+基准测试,将结果发送回打印。

from threading import Thread

class Alter(Thread):
    def __init__(self, word):
        Thread.__init__(self)
        self.word = word
        self.word2 = ''

    def run(self):
        # Alter string + test processing speed
        for i in range(80000):
            self.word2 = self.word2 + self.word

# Send a string to be altered
thread1 = Alter('foo')
thread2 = Alter('bar')
thread1.start()
thread2.start()

#wait for both to finish
while thread1.is_alive() == True: pass
while thread2.is_alive() == True: pass


print(thread1.word2)
print(thread2.word2)

这目前大约需要 6 秒,我需要它更快。
我一直在研究多处理,但找不到与上述代码等效的东西。我认为我所追求的是汇集,但我发现的例子很难理解。我想利用所有内核(8 个内核)multiprocessing.cpu_count(),但我真的只有一些关于多处理的有用信息,不足以复制上述代码。如果有人能指出我正确的方向或更好的方向,请提供一个将不胜感激的例子。请 Python 3

4

1 回答 1

8

只需替换threadingmultiprocessing和。Pyton 中的线程(几乎)从未用于获得性能,因为 GIL 非常糟糕!我在另一篇SO-post中对其进行了解释,其中包含一些文档链接以及关于 python 线程的精彩讨论。ThreadProcess

但是多处理模块故意与线程模块非常相似。您几乎可以将其用作替代品!

多处理模块不 AFAIK 提供强制使用特定数量内核的功能。它依赖于操作系统的实现。您可以使用 Pool 对象并将 worker-onjects 限制为核心计数。或者您可以寻找其他 MPI 库,例如 pypar。在 Linux 下,您可以使用 shell 下的管道在不同的内核上启动多个实例

于 2012-01-08T02:55:53.833 回答