本节主要讲解:协程访问网络+函数返回值获取
event_loop 事件循环: 程序开始循环,程序员会把一些函数(协程)注册带事件循环上。当满足事情发生时,调用相应的协程函数。
tasks 任务: asyncio 模块非常容易和方便的执行并发任务, 并且可以实现创建、取消等管理任务。
async/await 关键字:python3.5用于定义协程的关键字,async定义一个协程,await用于挂起阻塞的异步调用接口
import aiohttp #支持异步协程的requests
import asyncio
import time
begin=time.time()
async def task1():
url = 'https://www.baidu.com/'
s=aiohttp.ClientSession()#创建会话
r=await s.get(url)
html1=await r.text()
await s.close()#关闭会话
print(html1)
return 'task1'
event_loop=asyncio.get_event_loop()#事件循环创建
tasks=asyncio.gather(
asyncio.ensure_future(task1())#ensure_future创建任务
)
event_loop.run_until_complete(tasks)
event_loop.close()
print('返回值:',tasks.result())#协程函数返回值获取方法
finish=time.time()
print('time:',finish-begin)
运行结果
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
返回值: ['task1']
time: 0.3262300491333008
可以发现,对百度发起进行一次请求耗时0.326s,接下来,在tasks添加10个相同的任务
import aiohttp #支持异步协程的requests
import asyncio
import time
begin=time.time()
async def task1():
url = 'https://www.baidu.com/'
s=aiohttp.ClientSession()#创建会话
r=await s.get(url)
html1=await r.text()
await s.close()#关闭会话
print(html1)
return 'task1'
event_loop=asyncio.get_event_loop()#事件循环创建
tasks=asyncio.gather(
asyncio.ensure_future(task1()),#ensure_future创建任务
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1()),
asyncio.ensure_future(task1())
)
event_loop.run_until_complete(tasks)
event_loop.close()
print('返回值:',tasks.result())
finish=time.time()
print('time:',finish-begin)
运行结果
返回值: ['task1', 'task1', 'task1', 'task1', 'task1', 'task1', 'task1', 'task1', 'task1', 'task1']
time: 0.4453425407409668
可以发现,时间确实变短了,理论上0.326*10=3.26s,实际耗时0.445s。
拓展:笔者想知道计算机的执行速度,1s可以执行多少代码?
分别对单个任务和多个任务进行了十次测试:
单次用时[0.41,0.38,0.35,0.37,0.33,0.33,0.32,0.38,0.31,0.41],平均值0.359s;
多次用时[0.45,0.46,0.44,0.43,0.43,0.42,0.45,0.43,0.41,0.41],平均值0.433s;
0.433-0.359=0.074,每加一个任务会多执行10条代码,也就是0.074s执行了90条代码,那么一秒钟可以执行多少代码呢?
1/0.074*90=1216.21622,也就是1216条代码。可谓是弹指一挥间,代码已万行。