Python 多进程、多线程效率对比
作者:massquantity 发布时间:2022-01-23 00:54:24
Python 界有条不成文的准则: 计算密集型任务适合多进程,IO 密集型任务适合多线程。本篇来作个比较。
通常来说多线程相对于多进程有优势,因为创建一个进程开销比较大,然而因为在 python 中有 GIL 这把大锁的存在,导致执行计算密集型任务时多线程实际只能是单线程。而且由于线程之间切换的开销导致多线程往往比实际的单线程还要慢,所以在 python 中计算密集型任务通常使用多进程,因为各个进程有各自独立的 GIL,互不干扰。
而在 IO 密集型任务中,CPU 时常处于等待状态,操作系统需要频繁与外界环境进行交互,如读写文件,在网络间通信等。在这期间 GIL 会被释放,因而就可以使用真正的多线程。
以上是理论,下面做一个简单的模拟测试: 大量计算用 math.sin() + math.cos()
来代替,IO 密集型用 time.sleep()
来模拟。 在 Python 中有多种方式可以实现多进程和多线程,这里一并纳入看看是否有效率差异:
多进程: joblib.multiprocessing, multiprocessing.Pool, multiprocessing.apply_async, concurrent.futures.ProcessPoolExecutor
多线程: 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 密集型任务速度: 多线程 > 多进程 > 单进程/线程。
来源:https://www.cnblogs.com/massquantity/p/10357898.html


猜你喜欢
- 1. 利用resnet18做迁移学习import torchfrom torchvision import models if __name
- 创建类from django.forms import ModelFormfrom django.forms import widgets
- 废话不多说,直接上代码吧~model.zero_grad()optimizer.zero_grad()首先,这两种方式都是把模型中参数的梯度
- try 块允许您测试代码块以查找错误。except 块允许您处理错误。finally 块允许您执行代码,无论 try 和 except 块的
- Python 3中的File对象不支持next()方法。 Python 3有一个内置函数next(),它通过调用其next ()方法从迭代器
- 假设当我们只需知道某个数组有没有某个属性,如果找到了直接跳出循环,省略掉剩下的循环步骤是较优化的操作,但是for中是可以利用break跳出循
- 实现制作抽奖程序,需要认知到我们可以看到一般抽奖程序界面上是有很多按钮的,比如中奖区域,按键开始区域等等,所以我们先要设置界面,然后把这些按
- 先来看一段代码:# ~*~ Twisted - A Python tale ~*~from time import sleep# Hello
- 误区 #30:有关备份的30个误区全是错的在开始有关备份的误区之前,如果你对备份的基础没有了解,请看之前我在TechNet Magazine
- 一、PyTorch批训练1. 概述PyTorch提供了一种将数据包装起来进行批训练的工具——DataLoader。使用的时候,只需要将我们的
- 导语哈喽铁汁们好久不见吖~小编已经复工了于是马不停蹄赶来给大家准备新年礼物算开工礼物吧!海龟来作图虎年就是要画老虎2022不用纸和笔~今晚画
- 本文较为详细的罗列了Python常见的异常处理,供大家参考,具体如下:1. 抛出异常和自定义异常Python用异常对象(exception
- 总览在Python中,您需要通过打开文件来访问文件。您可以使用 open()函数来实现。Open 返回一个文件对象,该文件对象具有用于获取有
- 本篇介绍Python中的引用。首先想一想如图示例。在python中,值是靠引用来传递来的。用id()来判断两个变量是否为同一个值的引用。如图
- 本文实例为大家分享了JS作用域链的相关内容,供大家参考,具体内容如下1、所有全局变量和函数都是作为window对象的属性和方法创建的。2、在
- 在进行PHP编程时,需要对服务器某个目录下面的文件进行浏览,通常成为遍历目录。取得一个目录下的文件和子目录,就需要用到opendir()函数
- 本文实例讲述了Python常见工厂函数用法。分享给大家供大家参考,具体如下:工厂函数:能够产生类实例的内建函数。 工厂函数是指这些
- Linux系统中的信号类型各操作系统的信号定义或许有些不同。下面列出了POSIX中定义的信号。在linux中使用34-64信号用作实时系统中
- 一年中秋至 又见圆月时导语假设农历八月十五,程序员错过了今年的中秋圆月。▼程序员的苦只有他们寄几知道bug,bug,bug,bug,bug,
- 我就废话不多说了,直接上代码吧!import turtlet=turtle.Turtle()turtle.Turtle().screen.d