python - 为什么 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 使用率会这样?
关于该图像的注释:
- 横轴 i 时间以秒为单位,纵轴是 cpu % 使用率,范围从 0% 到 100%。更新间隔为 1 秒。
- 40年代是我开始剧本的地方
- 不容易看到,但有16个核心。
另一个注意事项:我没有将 n_workers 设置为 16,因为我有 16 个内核。只是巧合。
那么为什么这会一次使用 75% 的 16 个内核呢?
解决方案
因为如果可以的话,您的线程池将使用每个线程 1 个核心。这就是提供最大并行性和最大化吞吐量的原因。
推荐阅读
- c# - PayPal Sandbox 执行调用返回错误 400 错误请求
- filetable - FileTable file_stream 列:“无法在 varbinary 上调用方法”
- android-studio - Flutter - 如何在图像下方使用带有图像和文本/图标的容器小部件
- python - TensorFlow Probability 和 PyTorch 中未实现正态和拉普拉斯的 KL 散度
- ruby-on-rails - 为什么 Trailblazer 会出现“没有将 Symbol 隐式转换为 Hash”的错误?
- mips32 - MIPS 基本存储(地址为零?)
- django - 无法使用 heroku 部署 django api
- python - 数学测验任务 3 在一个名字上保存 3 个分数
- python - Pandas DataFrame - 创建动态列数
- reactjs - 在 codepen 的反应组件中包含引导程序