目前计算机程序一般会遇到两类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. Bootstrap3基础 caret 辅助类样式 下拉的小三角

      内容 参数   OS   Windows 10 x64   browser   Firefox 65.0.2   framework     Bootstrap 3.3.7   editor    ...

  2. Python3基础 list len 输出元素的个数

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  3. 【做题】51NOD1753 相似子串——哈希

    题意:两个字符串相似定义为: 1.两个字符串长度相等 2.两个字符串对应位置上至多有一个位置所对应的字符不相同 给定一个字符串\(s\),\(T\)次询问两个子串在给定的规则下是否相似.给定的规则指每 ...

  4. vs 附加进程 iis进程显示

  5. (转)Introduction to Gradient Descent Algorithm (along with variants) in Machine Learning

    Introduction Optimization is always the ultimate goal whether you are dealing with a real life probl ...

  6. (转) GAN应用情况调研

    本文转自: https://mp.weixin.qq.com/s?__biz=MzA5MDMwMTIyNQ==&mid=2649290778&idx=1&sn=9816b862 ...

  7. Kylin简介

    来源 Cube: 用空间换时间(类似:BI分析) 预计算把用户需要查询的维度以及他们所对应的考量的值,存储在多维空间里 当用户查询某几个维度的时候,通过这些维度条件去定位到预计算的向量空间,通过再聚合 ...

  8. Qt打包

    先在Qt Creator里release一遍,打开Qt下载时自带的像命令控制台一样的东西,比如我在创建项目时选用的是MinGw编译器, 然后在文件管理器里找到release生成的exe,cd进exe所 ...

  9. js 字符串加密解密

    Welcome to jzzy.com

  10. C++中CopyFile、MoveFile的用法

    1.含义 CopyFile(A, B, FALSE);表示将文件A拷贝到B,如果B已经存在则覆盖(第三参数为TRUE时表示不覆盖) MoveFile(A, B);表示将文件A移动到B 2.函数原型 C ...