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

 更新时间:2020年11月19日 10:32:14   作者:massquantity  
这篇文章主要介绍了Python 多进程、多线程的效率对比,帮助大家选择适合的技术,感兴趣的朋友可以了解下

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使用描述符实现属性类型检查的案例解析

    这篇文章主要介绍了Python使用描述符实现属性类型检查,实例属性就是在一个类中将另一个类的实例作为该类的一个数属性,本文通过代码演示给大家介绍的非常详细,需要的朋友可以参考下
    2022-05-05
  • 零基础写python爬虫之爬虫编写全记录

    零基础写python爬虫之爬虫编写全记录

    前面九篇文章从基础到编写都做了详细的介绍了,第十篇么讲究个十全十美,那么我们就来详细记录一下一个爬虫程序如何一步步编写出来的,各位看官可要看仔细了
    2014-11-11
  • 在Python中使用turtle绘制多个同心圆示例

    在Python中使用turtle绘制多个同心圆示例

    今天小编就为大家分享一篇在Python中使用turtle绘制多个同心圆示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • Django模型层实现多表关系创建和多表操作

    Django模型层实现多表关系创建和多表操作

    使用django ORM可以创建多表关系,并且也支持多张表之间的操作,以创建表关系和查询两部分说明django ORM的多表操作,本文就详细的介绍一下,感兴趣的可以了解一下
    2021-07-07
  • PyCharm中Python解释器如何选择详析

    PyCharm中Python解释器如何选择详析

    这篇文章主要给大家介绍了关于PyCharm中Python解释器如何选择的相关资料,文中详细分析了四种常见的Python环境管理工具,分别是venv、conda、pipenv和poetry,需要的朋友可以参考下
    2024-11-11
  • 使用Pyinstaller的最新踩坑实战记录

    使用Pyinstaller的最新踩坑实战记录

    这篇文章主要给大家介绍了最近在使用Pyinstaller的踩坑实战记录,主要介绍了PYTHON2X.DLL缺失和WINDOWS2003 32BIT提示程序无效这两个问题的解决方法,文中给出了详细的解决方法,需要的朋友们下面来一起看看吧。
    2017-11-11
  • 使用Python处理数据集的技巧分享

    使用Python处理数据集的技巧分享

    这篇文章会从加载数据开始,一步步教大家如何格式化数据、保存数据,最后还会教大家如何加载处理后的数据,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-12-12
  • Python切片工具pillow用法示例

    Python切片工具pillow用法示例

    这篇文章主要介绍了Python切片工具pillow用法,结合实例形式分析了Python中pillow的简单安装与使用操作技巧,需要的朋友可以参考下
    2018-03-03
  • Python数据类型相互转换

    Python数据类型相互转换

    当涉及数据类型转换时,Python提供了多种内置函数来执行不同类型之间的转换,本文主要介绍了Python数据类型相互转换,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • Python 实现两个服务器之间文件的上传方法

    Python 实现两个服务器之间文件的上传方法

    今天小编就为大家分享一篇Python 实现两个服务器之间文件的上传方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-02-02

最新评论