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