从入门到精通,从精通到放弃,今天我们给大家说说放弃协程的原因
本次对协程进行测速,下面有三个实列,分别是:
1普通函数;
2协程封装一个task
3协程封装多个task
例1:普通函数
import asyncio,requests,time
def get_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
html=requests.get(url,headers=headers)
print(html)
def func1():
for i in range(10):
asyncio.sleep(0.2)
print('++++++++++++++++)')
get_html('http://www.baidu.com')
def func2():
for i in range(10):
asyncio.sleep(0.1)
print('-------------)')
get_html('http://www.4399.com')
if __name__ == '__main__':
begin=time.time()
func1()
func2()
print(time.time()-begin)
耗时:1.889108419418335
例2:协程封装一个task
import asyncio,requests,time
def get_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
html=requests.get(url,headers=headers)
print(html)
async def func1():
for i in range(10):
await asyncio.sleep(0.2)
print('++++++++++++++++)')
get_html('http://www.baidu.com')
async def func2():
for i in range(10):
await asyncio.sleep(0.1)
print('-------------)')
get_html('http://www.4399.com')
async def main():
await func1()
await func2()
if __name__ == '__main__':
begin=time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
print(time.time()-begin)
耗时:4.484957933425903
例3:协程封装多个task
import asyncio,requests,time
# url='http://www.baidu.com'
def get_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
html=requests.get(url,headers=headers)
print(html)
async def func1():
for i in range(10):
await asyncio.sleep(0.2)
print('++++++++++++++++)') # 异步 I/O 里面的 sleep() 方法, 它也是一个协程, 异步 I/O 里面不能使用 time.sleep(), time.sleep() 会阻塞整个线程
get_html('http://www.baidu.com')
async def func2():
for i in range(10):
await asyncio.sleep(0.1)
print('-------------)')
get_html('http://www.4399.com')
if __name__ == '__main__':
begin=time.time()
loop = asyncio.get_event_loop()
tasks = asyncio.gather( # gather() 可以将一些 future 和协程封装成一个 future
asyncio.ensure_future(func1()), # ensure_future() 可以将一个协程封装成一个 Task
asyncio.ensure_future(func2())
)
loop.run_until_complete(tasks)
loop.close()
print(time.time()-begin)
耗时:3.037881851196289
小量级:普通函数>协程封装多个task>协程封装一个task