我是个多处理机新手
我知道一些关于线程的知识,但是我需要提高这个计算的速度,希望是通过多处理:
Example Description: sends string to a thread, alters string + benchmark test, send result back for printing.
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()
,但我真的只有一些有用的信息,不足以重复上述代码。如果有人能给我指出正确的方向或更好的方向,请提供一个非常感谢的例子。请给我Python3号
只要用
multiprocessing
替换threading
,用Process
替换Thread
。Pyton中的线程(几乎)从未用于获得性能,因为有一个很大的坏GIL!我在另一个SO-post中解释了它,其中包含一些文档链接和great talk about threading in python.但是multiprocessing模块有意地非常类似于线程模块。你几乎可以用它作为替代品!
多处理模块不提供强制使用特定数量核心的功能。它依赖于操作系统的实现。您可以使用Pool对象并将worker对象限制为核心计数。或者你可以找一个其他的MPI库,比如pypar。在Linux下,可以使用shell下的管道在不同的内核上启动多个实例
相关问题 更多 >
编程相关推荐