Python多线程多进程实例对比解析
作者:我太难了008 时间:2022-10-09 16:43:20
多线程适合于多io操作
多进程适合于耗cpu(计算)的操作
# 多进程编程
# 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ProcessPoolExecutor
def fib(n):
if n <= 2:
return 1
return fib(n - 2) + fib(n - 1)
if __name__ == '__main__':
# 1. 对于耗cpu操作,多进程优于多线程
# with ThreadPoolExecutor(3) as executor:
# all_task = [executor.submit(fib, num) for num in range(25, 35)]
# start_time = time.time()
# for future in as_completed(all_task):
# data = future.result()
# print(data)
# print("last time :{}".format(time.time() - start_time)) # 3.905290126800537
# 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常
with ProcessPoolExecutor(3) as executor:
all_task = [executor.submit(fib, num) for num in range(25, 35)]
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print(data)
print("last time :{}".format(time.time() - start_time)) # 2.6130592823028564
可以看到在耗cpu的应用中,多进程明显优于多线程 2.6130592823028564 < 3.905290126800537
下面模拟一个io操作
# 多进程编程
# 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ProcessPoolExecutor
def io_operation(n):
time.sleep(2)
return n
if __name__ == '__main__':
# 1. 对于耗cpu操作,多进程优于多线程
# with ThreadPoolExecutor(3) as executor:
# all_task = [executor.submit(io_operation, num) for num in range(25, 35)]
# start_time = time.time()
# for future in as_completed(all_task):
# data = future.result()
# print(data)
# print("last time :{}".format(time.time() - start_time)) # 8.00358772277832
# 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常
with ProcessPoolExecutor(3) as executor:
all_task = [executor.submit(io_operation, num) for num in range(25, 35)]
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print(data)
print("last time :{}".format(time.time() - start_time)) # 8.12435245513916
可以看到 8.00358772277832 < 8.12435245513916, 即是多线程比多进程更牛逼!
来源:https://www.cnblogs.com/z-qinfeng/p/12064012.html
标签:Python,多,线程,进程
0
投稿
猜你喜欢
Python程序设计入门(3)数组的使用
2023-07-20 07:11:15
利用python实现在微信群刷屏的方法
2023-05-01 13:56:29
MySQL的查询计划中ken_len的值计算方法
2024-01-24 13:32:49
pycharm设置python文件模板信息过程图解
2023-03-21 14:46:22
使用线框图来简化你的产品设计流程
2011-06-10 13:10:00
tensorflow tf.train.batch之数据批量读取方式
2023-12-08 01:11:51
JS实现简洁、全兼容的拖动层实例
2024-04-19 09:49:08
利用二进制文件安装etcd的教程详解
2023-07-22 00:23:47
解决Microsoft VBScript 运行时错误 (0x800A0046) 没有权限的解决方案
2009-09-03 13:28:00
asp根据出生时间判断生肖
2008-03-24 19:49:00
ImageMagicK convert crop参数说明
2008-10-21 12:46:00
css学习笔记:DIV水平垂直居中
2009-06-19 12:45:00
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
2021-03-19 17:44:43
基于Python编写简易文字语音转换器
2023-12-28 19:24:54
如何使用Goland IDE go mod 方式构建项目
2024-02-23 00:36:40
django中只使用ModleForm的表单验证
2021-02-03 15:41:50
在Linux上安装Python的Flask框架和创建第一个app实例的教程
2021-08-26 14:23:11
初识Firebug 全文 — firebug的使用
2007-10-23 12:54:00
python实现ftp文件传输功能
2023-04-21 13:20:16
详解MySQL 8.0 之不可见索引
2024-01-22 17:41:46