快速使用 ThreadPoolExecutor 并行加速

总览#

一般的 Python 脚本只会用上单线程。对于 IO 密集型任务,用多线程加速会快得多。

本文会给出一个模板,使用 ThreadPoolExecutor 进行并行加速。

注意,由于 GIL 的存在,对于 CPU 密集型任务 ProcessPoolExecutor 是更好的选择。

快速使用 ThreadPoolExecutor#

请看以下模板。

from concurrent.futures import ThreadPoolExecutor

def process_file(file):
    with Image.open(file) as img:
        ···
    return result

files = [···]
with ThreadPoolExecutor() as executor:
    for result in executor.map(process_file, files):
        ···
  • process_file() 是需要多线程执行的函数
  • files 装着若干 process_file() 的输入。会以此生成若干个 process_file() 任务
  • executor.map() 返回一个迭代器

就这样,with ThreadPoolExecutor() as executor: 以内的代码会阻塞主线程,直到所有任务运行完毕。而 executor.map(process_file, files) 所生成的任务会并行运行,每次的运行结果会按顺序装入 result,用于遍历结果。

作者:chirp

出处:https://www.cnblogs.com/chirp/p/18238899

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   倒地  阅读(196)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示