我是一个多处理新手,
我对线程有所了解,但我需要提高这种计算的速度,希望通过多处理:
示例描述:将字符串发送到线程,更改字符串+基准测试,将结果发送回打印。
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