首页 > 解决方案 > 为什么 ThreadPool 会导致超过一个核心的 CPU 使用率?

问题描述

我有如下代码:

def get_image_stats(fp):
    img = cv2.imread(fp)
    return img.shape[0], img.shape[1], img.shape[0]/img.shape[1]

with ThreadPool(16) as pool:
    res = list(tqdm(pool.imap_unordered(get_image_stats, df.file_path), total=len(df)))

heights, widths, ars = list(zip(*res))

唯一的库特定部分cv2.imread只是将图像文件加载到 numpy 数组中,因此它是 I/O 绑定的。

为什么我的 CPU 使用率会这样?

在此处输入图像描述

关于该图像的注释:

另一个注意事项:我没有将 n_workers 设置为 16,因为我有 16 个内核。只是巧合。

那么为什么这会一次使用 75% 的 16 个内核呢?

标签: pythonmultiprocessing

解决方案


因为如果可以的话,您的线程池将使用每个线程 1 个核心。这就是提供最大并行性和最大化吞吐量的原因。


推荐阅读