Python多线程太慢,使用多进程
我刚接触多进程,
我对线程有一些了解,但我需要加快这个计算的速度,希望能用多进程来实现:
示例描述:把字符串发送到一个线程,修改字符串 + 基准测试,然后把结果发送回来打印。
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。
1 个回答
10
只需要把 threading
替换成 multiprocessing
,把 Thread
替换成 Process
。在Python中,线程(Thread)几乎从来不是用来提高性能的,因为有个叫做GIL的东西在捣乱!我在另一个帖子里解释过这个问题,还提供了一些文档链接和一个关于Python中线程的精彩讲座。
不过,multiprocessing模块的设计故意和线程模块很相似。你几乎可以直接把它当作替代品来用!
据我所知,multiprocessing模块并没有提供强制使用特定数量核心的功能。它依赖于操作系统的实现。你可以使用Pool对象,并把工作对象的数量限制在核心数量内。或者你可以寻找其他的MPI库,比如pypar。在Linux下,你可以通过命令行管道来启动多个实例在不同的核心上运行。