繁体   English   中英

Python,多线程太慢,多进程

[英]Python, multithreading too slow, 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) 

目前大约需要6秒钟,我需要它加快速度。
我一直在研究多处理,找不到与上述代码等效的东西。 我认为我的追求是集中精力,但是我发现的例子很难理解。 我想利用所有内核(8个内核) multiprocessing.cpu_count()优势,但实际上我只是获得了有关多处理的有用信息的片段,不足以重复上述代码。 如果有人可以指出正确的方向或更好的方向,请提供一个示例,将不胜感激。 请使用Python 3

只需将threading替换为multiprocessing并将Thread替换为Process 由于存在严重的GIL,Pyton中的线程几乎(几乎)从未用于获得性能! 我在另一篇SO-post中对此进行了解释,并提供了一些文档链接和有关python线程大量论述。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM