【发布时间】: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