目前计算机程序一般会遇到两类I/O:硬盘I/O和网络I/O。我就针对网络I/O的场景分析下python3下进程、线程、协程效率的对比。进程采用multiprocessing.Pool进程池,线程是自己封装的进程池,协程采用gevent的库。用python3自带的urlllib.request和开源的requests做对比。代码如下:

import urllib.request
import requests
import time
import multiprocessing
import threading
import queue def startTimer():
return time.time() def ticT(startTime):
useTime = time.time() - startTime
return round(useTime, 3) #def tic(startTime, name):
# useTime = time.time() - startTime
# print('[%s] use time: %1.3f' % (name, useTime)) def download_urllib(url):
req = urllib.request.Request(url,
headers={'user-agent': 'Mozilla/5.0'})
res = urllib.request.urlopen(req)
data = res.read()
try:
data = data.decode('gbk')
except UnicodeDecodeError:
data = data.decode('utf8', 'ignore')
return res.status, data def download_requests(url):
req = requests.get(url,
headers={'user-agent': 'Mozilla/5.0'})
return req.status_code, req.text class threadPoolManager:
def __init__(self,urls, workNum=10000,threadNum=20):
self.workQueue=queue.Queue()
self.threadPool=[]
self.__initWorkQueue(urls)
self.__initThreadPool(threadNum) def __initWorkQueue(self,urls):
for i in urls:
self.workQueue.put((download_requests,i)) def __initThreadPool(self,threadNum):
for i in range(threadNum):
self.threadPool.append(work(self.workQueue)) def waitAllComplete(self):
for i in self.threadPool:
if i.isAlive():
i.join() class work(threading.Thread):
def __init__(self,workQueue):
threading.Thread.__init__(self)
self.workQueue=workQueue
self.start()
def run(self):
while True:
if self.workQueue.qsize():
do,args=self.workQueue.get(block=False)
do(args)
self.workQueue.task_done()
else:
break urls = ['http://www.ustchacker.com'] * 10
urllibL = []
requestsL = []
multiPool = []
threadPool = []
N = 20
PoolNum = 100 for i in range(N):
print('start %d try' % i)
urllibT = startTimer()
jobs = [download_urllib(url) for url in urls]
#for status, data in jobs:
# print(status, data[:10])
#tic(urllibT, 'urllib.request')
urllibL.append(ticT(urllibT))
print('') requestsT = startTimer()
jobs = [download_requests(url) for url in urls]
#for status, data in jobs:
# print(status, data[:10])
#tic(requestsT, 'requests')
requestsL.append(ticT(requestsT))
print('') requestsT = startTimer()
pool = multiprocessing.Pool(PoolNum)
data = pool.map(download_requests, urls)
pool.close()
pool.join()
multiPool.append(ticT(requestsT))
print('') requestsT = startTimer()
pool = threadPoolManager(urls, threadNum=PoolNum)
pool.waitAllComplete()
threadPool.append(ticT(requestsT))
print('') import matplotlib.pyplot as plt
x = list(range(1, N+1))
plt.plot(x, urllibL, label='urllib')
plt.plot(x, requestsL, label='requests')
plt.plot(x, multiPool, label='requests MultiPool')
plt.plot(x, threadPool, label='requests threadPool')
plt.xlabel('test number')
plt.ylabel('time(s)')
plt.legend()
plt.show()

运行结果如下:

从上图可以看出,python3自带的urllib.request效率还是不如开源的requests,multiprocessing进程池效率明显提升,但还低于自己封装的线程池,有一部分原因是创建、调度进程的开销比创建线程高(测试程序中我把创建的代价也包括在里面)。

在Windows上要想使用进程模块,就必须把有关进程的代码写在当前.py文件的if __name__ == ‘__main__’ :语句的下面,才能正常使用Windows下的进程模块。Unix/Linux下则不需要。

下面是gevent的测试代码:

import urllib.request
import requests
import time
import gevent.pool
import gevent.monkey gevent.monkey.patch_all() def startTimer():
return time.time() def ticT(startTime):
useTime = time.time() - startTime
return round(useTime, 3) #def tic(startTime, name):
# useTime = time.time() - startTime
# print('[%s] use time: %1.3f' % (name, useTime)) def download_urllib(url):
req = urllib.request.Request(url,
headers={'user-agent': 'Mozilla/5.0'})
res = urllib.request.urlopen(req)
data = res.read()
try:
data = data.decode('gbk')
except UnicodeDecodeError:
data = data.decode('utf8', 'ignore')
return res.status, data def download_requests(url):
req = requests.get(url,
headers={'user-agent': 'Mozilla/5.0'})
return req.status_code, req.text urls = ['http://www.ustchacker.com'] * 10
urllibL = []
requestsL = []
reqPool = []
reqSpawn = []
N = 20
PoolNum = 100 for i in range(N):
print('start %d try' % i)
urllibT = startTimer()
jobs = [download_urllib(url) for url in urls]
#for status, data in jobs:
# print(status, data[:10])
#tic(urllibT, 'urllib.request')
urllibL.append(ticT(urllibT))
print('') requestsT = startTimer()
jobs = [download_requests(url) for url in urls]
#for status, data in jobs:
# print(status, data[:10])
#tic(requestsT, 'requests')
requestsL.append(ticT(requestsT))
print('') requestsT = startTimer()
pool = gevent.pool.Pool(PoolNum)
data = pool.map(download_requests, urls)
#for status, text in data:
# print(status, text[:10])
#tic(requestsT, 'requests with gevent.pool')
reqPool.append(ticT(requestsT))
print('') requestsT = startTimer()
jobs = [gevent.spawn(download_requests, url) for url in urls]
gevent.joinall(jobs)
#for i in jobs:
# print(i.value[0], i.value[1][:10])
#tic(requestsT, 'requests with gevent.spawn')
reqSpawn.append(ticT(requestsT))
print('') import matplotlib.pyplot as plt
x = list(range(1, N+1))
plt.plot(x, urllibL, label='urllib')
plt.plot(x, requestsL, label='requests')
plt.plot(x, reqPool, label='requests geventPool')
plt.plot(x, reqSpawn, label='requests Spawn')
plt.xlabel('test number')
plt.ylabel('time(s)')
plt.legend()
plt.show()

运行结果如下:

从上图可以看到,对于I/O密集型任务,gevent还是能对性能做很大提升的,由于协程的创建、调度开销都比线程小的多,所以可以看到不论使用gevent的Spawn模式还是Pool模式,性能差距不大。

因为在gevent中需要使用monkey补丁,会提高gevent的性能,但会影响multiprocessing的运行,如果要同时使用,需要如下代码:

gevent.monkey.patch_all(thread=False, socket=False, select=False)

可是这样就不能充分发挥gevent的优势,所以不能把multiprocessing Pool、threading Pool、gevent Pool在一个程序中对比。不过比较两图可以得出结论,线程池和gevent的性能最优的,其次是进程池。附带得出个结论,requests库比urllib.request库性能要好一些哈:-)

转载请注明:转自http://blog.csdn.net/littlethunder/article/details/40983031

python3-----多进程、多线程、多协程的更多相关文章

  1. 也说性能测试,顺便说python的多进程+多线程、协程

    最近需要一个web系统进行接口性能测试,这里顺便说一下性能测试的步骤吧,大概如下 一.分析接口频率 根据系统的复杂程度,接口的数量有多有少,应该优先对那些频率高,数据库操作频繁的接口进行性能测试,所以 ...

  2. python3多进程 进程池 协程并发

    一.进程           我们电脑的应用程序,都是进程,进程是资源分配的单位.进程切换需要的资源最大,效率低.         进程之间相互独立         cpu密集的时候适合用多进程 #多 ...

  3. python基础整理5——多进程多线程和协程

    进程与线程 1.进程 我们电脑的应用程序,都是进程,假设我们用的电脑是单核的,cpu同时只能执行一个进程.当程序处于I/O阻塞的时候,CPU如果和程序一起等待,那就太浪费了,cpu会去执行其他的程序, ...

  4. python 多进程,多线程,协程

    在我们实际编码中,会遇到一些并行的任务,因为单个任务无法最大限度的使用计算机资源.使用并行任务,可以提高代码效率,最大限度的发挥计算机的性能.python实现并行任务可以有多进程,多线程,协程等方式. ...

  5. 深入浅析python中的多进程、多线程、协程

    深入浅析python中的多进程.多线程.协程 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源 ...

  6. python3 - 多线程和协程速率测试对比

    多线程和协程都属于IO密集型,我通过以下用例测试多线程和协程的实际速率对比. 实例:通过socket客户端以多线程并发模式请求不同服务器端(这里服务器端分2种写法:第一种服务器通过协程实现,第二种服务 ...

  7. Python并发编程——多线程与协程

    Pythpn并发编程--多线程与协程 目录 Pythpn并发编程--多线程与协程 1. 进程与线程 1.1 概念上 1.2 多进程与多线程--同时执行多个任务 2. 并发和并行 3. Python多线 ...

  8. python单线程,多线程和协程速度对比

    在某些应用场景下,想要提高python的并发能力,可以使用多线程,或者协程.比如网络爬虫,数据库操作等一些IO密集型的操作.下面对比python单线程,多线程和协程在网络爬虫场景下的速度. 一,单线程 ...

  9. Python多进程、多线程和协程简介

    一.进程和线程 进程是一个执行中的程序.每个进程都拥有自己的地址空间.内存.数据栈以及其他用于跟踪执行的辅助数据.在单核CPU系统中的多进程,内存中可以有许多程序,但在给定一个时刻只有一个程序在运行: ...

  10. Python多进程、多线程、协程

    转载:https://www.cnblogs.com/huangguifeng/p/7632799.html 首先我们来了解下python中的进程,线程以及协程! 从计算机硬件角度: 计算机的核心是C ...

随机推荐

  1. Docker 入门指南——Dockerfile 指令

    COPY 复制文件 格式: COPY [--chown=<user>:<group>] <源路径>... <目标路径> 源路径可以是多个,甚至可以使通配 ...

  2. 2018年第九届蓝桥杯B组题C++汇总解析-fishers

    2018年第九届蓝桥杯B组题C++解析-fishers 题型 第一题:第几天 第二题:明码 第三题:乘积尾零 第四题:测试次数 第五题:快速排序 第六题:递增三元组 第七题:螺旋折线 第八题:日志统计 ...

  3. powershell脚本的格式化

    Auto Formatting PowerShell in Visual Studio Code 1.安装visual studio code 2.安装powershell extension 3.打 ...

  4. B树,B+树比较

    首先注意:B树就是B-树,"-"是个连字符号,不是减号.也就是B-树其实就是B树 B-树是一种平衡的多路查找(又称排序)树,在文件系统中有所应用.主要用作文件的索引.其中的B就表示 ...

  5. 【转载】ASP.NET页面之间传值的方式之QueryString(个人整理)

    转自: https://www.cnblogs.com/kudsu/p/7694637.html QueryString Querystring也叫查询字符串,这种页面间传递数据是利用网页地址URL. ...

  6. HDU 1251 统计难题(字典树模板题)

    http://acm.hdu.edu.cn/showproblem.php?pid=1251 题意:给出一些单词,然后有多次询问,每次输出以该单词为前缀的单词的数量. 思路: 字典树入门题. #inc ...

  7. BZOJ 1037: [ZJOI2008]生日聚会Party(区间dp)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1037 题意: 思路: 四维数组进行dp,dp[i][j][a][b]表示进行到第i个座位时已经有j个 ...

  8. Web前端新手经典学习路线

    做前端开发八九年的时间,到2015年的时候,Web前端因为HTML5技术的高速发展,成为IT行业中最受欢迎和未来需求人才发展最好的职业,各个行业都想转行做前端开发,包括一些在校的学生,土木工程,一些不 ...

  9. 新加坡金融科技节 | 蚂蚁金服CTO程立:面向全球开放,与合作伙伴共赢

    小蚂蚁说: 11月13日,在新加坡金融科技节上,蚂蚁金服CTO程立分别从TechFin.BASIC战略.SOFAStack全栈分布式体系以及全面开放等方面讲述蚂蚁金融科技. TechFin是一种“倒立 ...

  10. Oracle(限定查询1)

    3.1.认识限定查询 例如:如果一张表中有100w条数据,一旦执行了“SELECT * FROM 表”语句之后,则将在屏幕上显示表中的全部数据行的记录,这样即不方便浏览,也有可能造成死机的问题出现,所 ...