Python,多线程太慢,多进程

Rhy*_*hys 5 python multithreading pool multiprocess

我是一个多处理新手,

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

Don*_*ion 7

只需更换threadingmultiprocessingThreadProcess.Pyton中的线程(几乎)从未用于获得性能,因为GIL很糟糕!我在另一个SO帖子中解释了它,其中包含一些文档链接以及关于python中线程精彩演讲.

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

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