Python 多进程、多线程效率对比


Posted in Python onNovember 19, 2020

Python 界有条不成文的准则: 计算密集型任务适合多进程,IO 密集型任务适合多线程。本篇来作个比较。

通常来说多线程相对于多进程有优势,因为创建一个进程开销比较大,然而因为在 python 中有 GIL 这把大锁的存在,导致执行计算密集型任务时多线程实际只能是单线程。而且由于线程之间切换的开销导致多线程往往比实际的单线程还要慢,所以在 python 中计算密集型任务通常使用多进程,因为各个进程有各自独立的 GIL,互不干扰。

而在 IO 密集型任务中,CPU 时常处于等待状态,操作系统需要频繁与外界环境进行交互,如读写文件,在网络间通信等。在这期间 GIL 会被释放,因而就可以使用真正的多线程。

以上是理论,下面做一个简单的模拟测试: 大量计算用 math.sin() + math.cos() 来代替,IO 密集型用 time.sleep() 来模拟。 在 Python 中有多种方式可以实现多进程和多线程,这里一并纳入看看是否有效率差异:

  1. 多进程: joblib.multiprocessing, multiprocessing.Pool, multiprocessing.apply_async, concurrent.futures.ProcessPoolExecutor
  2. 多线程: joblib.threading, threading.Thread, concurrent.futures.ThreadPoolExecutor
from multiprocessing import Pool
from threading import Thread
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time, os, math
from joblib import Parallel, delayed, parallel_backend


def f_IO(a): # IO 密集型
 time.sleep(5)

def f_compute(a): # 计算密集型
 for _ in range(int(1e7)):
  math.sin(40) + math.cos(40)
 return

def normal(sub_f):
 for i in range(6):
  sub_f(i)
 return

def joblib_process(sub_f):
 with parallel_backend("multiprocessing", n_jobs=6):
  res = Parallel()(delayed(sub_f)(j) for j in range(6))
 return


def joblib_thread(sub_f):
 with parallel_backend('threading', n_jobs=6):
  res = Parallel()(delayed(sub_f)(j) for j in range(6))
 return

def mp(sub_f):
 with Pool(processes=6) as p:
  res = p.map(sub_f, list(range(6)))
 return

def asy(sub_f):
 with Pool(processes=6) as p:
  result = []
  for j in range(6):
   a = p.apply_async(sub_f, args=(j,))
   result.append(a)
  res = [j.get() for j in result]

def thread(sub_f):
 threads = []
 for j in range(6):
  t = Thread(target=sub_f, args=(j,))
  threads.append(t)
  t.start()
 for t in threads:
  t.join()

def thread_pool(sub_f):
 with ThreadPoolExecutor(max_workers=6) as executor:
  res = [executor.submit(sub_f, j) for j in range(6)]

def process_pool(sub_f):
 with ProcessPoolExecutor(max_workers=6) as executor:
  res = executor.map(sub_f, list(range(6)))

def showtime(f, sub_f, name):
 start_time = time.time()
 f(sub_f)
 print("{} time: {:.4f}s".format(name, time.time() - start_time))

def main(sub_f):
 showtime(normal, sub_f, "normal")
 print()
 print("------ 多进程 ------")
 showtime(joblib_process, sub_f, "joblib multiprocess")
 showtime(mp, sub_f, "pool")
 showtime(asy, sub_f, "async")
 showtime(process_pool, sub_f, "process_pool")
 print()
 print("----- 多线程 -----")
 showtime(joblib_thread, sub_f, "joblib thread")
 showtime(thread, sub_f, "thread")
 showtime(thread_pool, sub_f, "thread_pool")


if __name__ == "__main__":
 print("----- 计算密集型 -----")
 sub_f = f_compute
 main(sub_f)
 print()
 print("----- IO 密集型 -----")
 sub_f = f_IO
 main(sub_f)

结果:

----- 计算密集型 -----
normal time: 15.1212s

------ 多进程 ------
joblib multiprocess time: 8.2421s
pool time: 8.5439s
async time: 8.3229s
process_pool time: 8.1722s

----- 多线程 -----
joblib thread time: 21.5191s
thread time: 21.3865s
thread_pool time: 22.5104s



----- IO 密集型 -----
normal time: 30.0305s

------ 多进程 ------
joblib multiprocess time: 5.0345s
pool time: 5.0188s
async time: 5.0256s
process_pool time: 5.0263s

----- 多线程 -----
joblib thread time: 5.0142s
thread time: 5.0055s
thread_pool time: 5.0064s

上面每一方法都统一创建6个进程/线程,结果是计算密集型任务中速度:多进程 > 单进程/线程 > 多线程, IO 密集型任务速度: 多线程 > 多进程 > 单进程/线程。

以上就是Python 多进程、多线程效率比较的详细内容,更多关于Python 多进程、多线程的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
详解使用Python处理文件目录的相关方法
Oct 16 Python
Python并发编程协程(Coroutine)之Gevent详解
Dec 27 Python
Django框架实现分页显示内容的方法详解
May 10 Python
OpenCV 边缘检测
Jul 10 Python
对python3中的RE(正则表达式)-详细总结
Jul 23 Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
Feb 19 Python
Jupyter Notebook折叠输出的内容实例
Apr 22 Python
Python格式化输出--%s,%d,%f的代码解析
Apr 29 Python
python爬虫基础知识点整理
Jun 02 Python
tensorflow 2.0模式下训练的模型转成 tf1.x 版本的pb模型实例
Jun 22 Python
Anaconda使用IDLE的实现示例
Sep 23 Python
Python中Numpy和Matplotlib的基本使用指南
Nov 02 Python
Python导入父文件夹中模块并读取当前文件夹内的资源
Nov 19 #Python
Pytorch实验常用代码段汇总
Nov 19 #Python
Ubuntu配置Pytorch on Graph (PoG)环境过程图解
Nov 19 #Python
python基于pygame实现飞机大作战小游戏
Nov 19 #Python
Python numpy大矩阵运算内存不足如何解决
Nov 19 #Python
python3 os进行嵌套操作的实例讲解
Nov 19 #Python
如何创建一个Flask项目并进行简单配置
Nov 18 #Python
You might like
php伪静态之APACHE篇
2014/06/02 PHP
php实现在服务器端调整图片大小的方法
2015/06/16 PHP
phpmyadmin下载、安装、配置教程
2017/05/16 PHP
Laravel框架中VerifyCsrfToken报错问题的解决
2017/08/30 PHP
解决laravel查询构造器中的别名问题
2019/10/17 PHP
效率高的Javscript字符串替换函数的benchmark
2008/08/02 Javascript
JSON 入门指南 想了解json的朋友可以看下
2009/08/26 Javascript
JS读取cookies信息(记录用户名)
2012/01/10 Javascript
JS实现多物体缓冲运动实例代码
2013/11/29 Javascript
判断javascript的数据类型(示例代码)
2013/12/11 Javascript
JS、CSS以及img对DOMContentLoaded事件的影响
2014/08/12 Javascript
JS扩展类,克隆对象与混合类实例分析
2016/11/26 Javascript
js自制图片放大镜功能
2017/01/24 Javascript
用纯Node.JS弹出Windows系统消息提示框实例(MessageBox)
2017/05/17 Javascript
NodeJS 中Stream 的基本使用
2018/07/30 NodeJs
vue-cli中vue本地实现跨域调试接口
2019/01/16 Javascript
Elementui表格组件+sortablejs实现行拖拽排序的示例代码
2019/08/28 Javascript
使用js实现单链解决前端队列问题的方法
2020/02/03 Javascript
ES6对象操作实例详解
2020/05/23 Javascript
vue2和vue3的v-if与v-for优先级对比学习
2020/10/10 Javascript
[02:48]DOTA2超级联赛专访海涛:你们的选择没有错
2013/06/07 DOTA
[01:02:03]2014 DOTA2华西杯精英邀请赛 5 24 NewBee VS VG
2014/05/26 DOTA
用PyInstaller把Python代码打包成单个独立的exe可执行文件
2018/05/26 Python
python如何生成网页验证码
2018/07/28 Python
为什么说Python可以实现所有的算法
2019/10/04 Python
Pytorch 数据加载与数据预处理方式
2019/12/31 Python
TIME时代杂志台湾总代理:台时亚洲
2018/10/22 全球购物
工程力学专业毕业生求职信
2013/10/06 职场文书
工会换届选举方案
2014/05/21 职场文书
艺术学院毕业生求职信
2014/07/09 职场文书
保密工作整改情况汇报
2014/11/06 职场文书
调解书格式范本
2015/05/20 职场文书
让生命充满爱观后感
2015/06/08 职场文书
毕业季聚会祝酒词!
2019/07/04 职场文书
SQLServer2008提示评估期已过解决方案
2021/04/12 SQL Server
python opencv人脸识别考勤系统的完整源码
2021/04/26 Python