【问题标题】:Python Multi-threading CPU workloadPython 多线程 CPU 工作负载
【发布时间】:2021-03-15 11:09:34
【问题描述】:

我们尝试使用线程在 Python 中并行化我们的程序。问题是,我们没有得到 100% 的 CPU 使用率。 CPU 使用所有 8 个内核,但仅使用大约 50-60% 有时会更低。为什么 CPU 不能在 100% 的计算工作负载下工作?

我们在 Windows 上使用 Python 编程。

这是我们的多线程实现:

from threading import Thread
import hashlib

class CalculationThread(Thread):
    def init(self, target: str):
        Thread.init(self)
        self.target = target

    def run(self):
        for i in range(1000):
            hash_md5 = hashlib.md5()
            with open(str(self.target), "rb") as f:
                for chunk in iter(lambda: f.read(4096), b""):
                    hash_md5.update(chunk)
            f = hash_md5.hexdigest()
        print(self.getName() + "Finished")

threads = []
for i in range(20):
    t = CalculationThread(target="baden-wuerttemberg-latest.osm.pbf")
    print("Worker " + str(t.getName()) + " started")
    t.start()
    threads.append(t)

for t in threads:
    t.join()

运行计算时的 CPU 工作负载:

【问题讨论】:

  • 您使用 SSD 还是 HDD?我的意思是,瓶颈可能是磁盘 I/O。
  • 我们使用 SSD,这个有 1% 的工作负载,所以瓶颈应该不是 SSD 造成的。
  • 任务管理器不是检查工作量的最佳位置。 Sata-3 理论带宽只有 600 MB/s 和 20 个线程很多。我测试了您的代码,并在 Process Explorer 中获得了大约 460-470 MB/s I/O Delta Read Bytes。也许您最好尝试在 RAM 磁盘或 NVME 磁盘上运行您的代码,但我不确定。

标签: python windows multithreading cpu workload


【解决方案1】:

由于GIL的存在,python无法在多核多线程上实现真正的“并行”,尤其是计算密集型任务。

你得到了一些改进,因为你的任务也以某种方式受到 IO 的限制(你从磁盘读取)。

找出程序在多线程中执行的一种方法是使用一些多线程支持工具,例如VizTracer。它会告诉您在 md5 计算中花费了多少时间。

但是,真正并行执行此操作的正确方法是使用multiprocessing 库,可能是Pool 在多进程而不是多线程中执行此操作。

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多