1

我们尝试使用线程在 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 工作负载:

运行计算时的 CPU 工作负载

4

1 回答 1

0

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

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

弄清楚你的程序在多线程中做什么的一种方法是使用一些多线程支持工具,比如VizTracer。它会告诉您在 md5 计算中花费了多少时间。

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

于 2020-12-03T22:18:13.807 回答