我是多处理新手,
我了解一些有关线程的知识,但我需要提高计算速度,希望通过多重处理:
示例说明:将字符串发送到线程,更改字符串+基准测试,
将结果发回打印。
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 秒,我需要它跑得更快。
我一直在研究多重处理,但找不到与上述代码等效的东西。我想我所追求的是pooling但我发现的例子很难理解。我想利用所有核心(8 核)multiprocessing.cpu_count()
但我确实只有有关多处理的有用信息的碎片,不足以复制上述代码。如果有人能指出我正确的方向或更好的方向,请提供一个例子,我将不胜感激。请使用Python 3
只需更换threading
with multiprocessing
and Thread
with Process
。 Python 中的线程(几乎)从未用于获得性能,因为有一个大坏蛋!我在另一篇文章中解释过SO-post带有一些文档链接和关于 python 线程的精彩讨论。
But the 多重处理模块有意与线程模块非常相似。您几乎可以将它用作直接替代品!
据我所知,多处理模块不提供强制使用特定数量核心的功能。它依赖于操作系统的实现。您可以使用 Pool 对象并将工作对象限制为核心计数。或者您可以寻找其他 MPI 库,例如 pypar。在 Linux 下,您可以在 shell 下使用管道来启动不同内核上的多个实例
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)