Python中单线程、多线程和多进程的效率对比实验实例

作者:大囚长 时间:2022-12-01 09:25:55 

python的多进程性能要明显优于多线程,因为cpython的GIL对性能做了约束。

Python是运行在解释器中的语言,查找资料知道,python中有一个全局锁(GIL),在使用多进程(Thread)的情况下,不能发挥多核的优势。而使用多进程(Multiprocess),则可以发挥多核的优势真正地提高效率。

对比实验

资料显示,如果多线程的进程是CPU密集型的,那多线程并不能有多少效率上的提升,相反还可能会因为线程的频繁切换,导致效率下降,推荐使用多进程;如果是IO密集型,多线程进程可以利用IO阻塞等待时的空闲时间执行其他线程,提升效率。所以我们根据实验对比不同场景的效率

操作系统CPU内存硬盘
Windows 10双核8GB机械硬盘

(1)引入所需要的模块


import requests
import time
from threading import Thread
from multiprocessing import Process

(2)定义CPU密集的计算函数


def count(x, y):
 # 使程序完成150万计算
 c = 0
 while c < 500000:
   c += 1
   x += x
   y += y

(3)定义IO密集的文件读写函数


def write():
 f = open("test.txt", "w")
 for x in range(5000000):
   f.write("testwrite\n")
 f.close()

def read():
 f = open("test.txt", "r")
 lines = f.readlines()
 f.close()

(4) 定义网络请求函数


_head = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'}
url = "http://www.tieba.com"
def http_request():
 try:
   webPage = requests.get(url, headers=_head)
   html = webPage.text
   return {"context": html}
 except Exception as e:
   return {"error": e}

(5)测试线性执行IO密集操作、CPU密集操作所需时间、网络请求密集型操作所需时间


# CPU密集操作
t = time.time()
for x in range(10):
 count(1, 1)
print("Line cpu", time.time() - t)

# IO密集操作
t = time.time()
for x in range(10):
 write()
 read()
print("Line IO", time.time() - t)

# 网络请求密集型操作
t = time.time()
for x in range(10):
 http_request()
print("Line Http Request", time.time() - t)

输出

CPU密集:95.6059999466、91.57099986076355 92.52800011634827、 99.96799993515015
IO密集:24.25、21.76699995994568、21.769999980926514、22.060999870300293
网络请求密集型: 4.519999980926514、8.563999891281128、4.371000051498413、4.522000074386597、14.671000003814697

 (6)测试多线程并发执行CPU密集操作所需时间


counts = []
t = time.time()
for x in range(10):
 thread = Thread(target=count, args=(1,1))
 counts.append(thread)
 thread.start()

e = counts.__len__()
while True:
 for th in counts:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print(time.time() - t)

Output: 99.9240000248 、101.26400017738342、102.32200002670288

 (7)测试多线程并发执行IO密集操作所需时间


def io():
 write()
 read()

t = time.time()
ios = []
t = time.time()
for x in range(10):
 thread = Thread(target=count, args=(1,1))
 ios.append(thread)
 thread.start()

e = ios.__len__()
while True:
 for th in ios:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print(time.time() - t)

Output: 25.69700002670288、24.02400016784668

 (8)测试多线程并发执行网络密集操作所需时间


t = time.time()
ios = []
t = time.time()
for x in range(10):
 thread = Thread(target=http_request)
 ios.append(thread)
 thread.start()

e = ios.__len__()
while True:
 for th in ios:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print("Thread Http Request", time.time() - t)

Output: 0.7419998645782471、0.3839998245239258、0.3900001049041748

(9)测试多进程并发执行CPU密集操作所需时间


counts = []
t = time.time()
for x in range(10):
 process = Process(target=count, args=(1,1))
 counts.append(process)
 process.start()
e = counts.__len__()
while True:
 for th in counts:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print("Multiprocess cpu", time.time() - t)

Output: 54.342000007629395、53.437999963760376

 (10)测试多进程并发执行IO密集型操作


t = time.time()
ios = []
t = time.time()
for x in range(10):
 process = Process(target=io)
 ios.append(process)
 process.start()

e = ios.__len__()
while True:
 for th in ios:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print("Multiprocess IO", time.time() - t)

Output: 12.509000062942505、13.059000015258789

 (11)测试多进程并发执行Http请求密集型操作


t = time.time()
httprs = []
t = time.time()
for x in range(10):
 process = Process(target=http_request)
 ios.append(process)
 process.start()

e = httprs.__len__()
while True:
 for th in httprs:
   if not th.is_alive():
     e -= 1
 if e <= 0:
   break
print("Multiprocess Http Request", time.time() - t)

Output: 0.5329999923706055、0.4760000705718994

 实验结果

CPU密集型操作IO密集型操作网络请求密集型操作
线性操作94.9182499646922.461999952797.3296000004
多线程操作101.170000076224.86050009730.5053332647
多进程操作53.889999985712.78400003910.5045000315

通过上面的结果,我们可以看到:

多线程在IO密集型的操作下似乎也没有很大的优势(也许IO操作的任务再繁重一些就能体现出优势),在CPU密集型的操作下明显地比单线程线性执行性能更差,但是对于网络请求这种忙等阻塞线程的操作,多线程的优势便非常显著了

多进程无论是在CPU密集型还是IO密集型以及网络请求密集型(经常发生线程阻塞的操作)中,都能体现出性能的优势。不过在类似网络请求密集型的操作上,与多线程相差无几,但却更占用CPU等资源,所以对于这种情况下,我们可以选择多线程来执行

以上所述是小编给大家介绍的Python单线程多线程和多进程效率对比详解整合网站的支持!

来源:https://blog.csdn.net/Jailman/article/details/78427936

标签:Python,单线程,多线程,多进程
0
投稿

猜你喜欢

  • Vue 使用 Mint UI 实现左滑删除效果CellSwipe

    2024-05-10 14:16:45
  • MySQL事务的隔离级别详情

    2024-01-27 23:33:56
  • CSS应用的必要步骤:样式重设

    2008-06-11 13:29:00
  • Python实现霍夫圆和椭圆变换代码详解

    2022-12-22 19:32:29
  • Centos7安装和配置Mysql5.7

    2024-01-21 12:02:22
  • LotusPhp笔记之:基于ObjectUtil组件的使用分析

    2023-11-19 09:18:32
  • 模式化窗口

    2009-06-18 18:41:00
  • golang gorm更新日志执行SQL示例详解

    2024-04-23 09:46:24
  • 利用phpExcel实现Excel数据的导入导出(全步骤详细解析)

    2023-06-22 02:56:42
  • 手把手教你将Flask应用封装成Docker服务的实现

    2023-05-27 06:57:15
  • 矩形相交以及求出相交的区域的原理解析

    2023-08-17 18:39:09
  • Python字典生成式、集合生成式、生成器用法实例分析

    2021-04-06 08:06:31
  • Python3实现将一维数组按标准长度分隔为二维数组

    2021-10-24 16:46:20
  • 用Python的Django框架完成视频处理任务的教程

    2022-05-07 05:38:25
  • 浅谈keras中的batch_dot,dot方法和TensorFlow的matmul

    2023-04-08 07:21:28
  • Python 错误和异常代码详解

    2022-02-12 15:14:08
  • C#中通过使用Connection类来实现打开/关闭数据库的代码实例

    2024-01-21 22:36:55
  • 微信小程序报错: thirdScriptError的错误问题

    2024-04-19 09:47:43
  • IIS 301重定向与程序代码实现301重定向的差别

    2022-04-16 07:45:23
  • Python爬虫beautifulsoup4常用的解析方法总结

    2022-09-01 11:58:54
  • asp之家 网络编程 m.aspxhome.com