Python,多线程太慢,多进程

标签 python multithreading pool multiprocess

我是一个多处理新手,

我对线程有所了解,但我需要提高此计算的速度,希望通过多处理:

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() 但我实际上只有一些关于多处理的有用信息,不足以复制上面的代码。如果有人能指出我正确的方向或更好的方向,请提供一个示例,我们将不胜感激。请使用 Python 3

最佳答案

只需将 threading 替换为 multiprocessing 并将 Thread 替换为 Process。由于大坏 GIL,Pyton 中的线程(几乎)从未用于提高性能!我在另一个SO-post中解释了它带有一些文档链接和 great talk about threading in python.

但是multiprocessing模块有意与线程模块非常相似。您几乎可以将其用作直接替代品!

据我所知,多处理模块不提供强制使用特定数量内核的功能。它依赖于操作系统的实现。您可以使用 Pool 对象并将 worker-onjects 限制为核心数。或者您可以寻找其他 MPI 库,例如 pypar。在 Linux 下,您可以在 shell 下使用管道在不同的内核上启动多个实例

关于Python,多线程太慢,多进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774989/

相关文章:

multithreading - Rust 标准库中的线程局部变量是如何工作的?

python - multiprocessing.Pool 应该使用多少个处理器?

单进程的Python多处理速度

python - 多处理模块中 Pool 对象和 Manager 对象之间的位置

java - 如何从服务器连接两个客户端

python - setup.py 缺少 __init__.py 文件

python - IndexError尝试在python中数值求解差分方程

python使用多进程过滤海量文件

python - SqlAlchemy automap 不生成 Base.classes.[table_name]

VB.NET 如果我想锁定多个东西,我是否需要多个 SyncLocks?