快速使用 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
,用于遍历结果。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!