Python_協(xié)程_進階1

本節(jié)主要講解:協(xié)程訪問網(wǎng)絡+函數(shù)返回值獲取

event_loop 事件循環(huán): 程序開始循環(huán),程序員會把一些函數(shù)(協(xié)程)注冊帶事件循環(huán)上。當滿足事情發(fā)生時,調用相應的協(xié)程函數(shù)。
tasks 任務: asyncio 模塊非常容易和方便的執(zhí)行并發(fā)任務, 并且可以實現(xiàn)創(chuàng)建、取消等管理任務。
async/await 關鍵字:python3.5用于定義協(xié)程的關鍵字,async定義一個協(xié)程,await用于掛起阻塞的異步調用接口

import aiohttp #支持異步協(xié)程的requests
import asyncio
import time
begin=time.time()
async def task1():
    url = 'https://www.baidu.com/'
    s=aiohttp.ClientSession()#創(chuàng)建會話
    r=await s.get(url)
    html1=await r.text()
    await s.close()#關閉會話
    print(html1)
    return 'task1'
event_loop=asyncio.get_event_loop()#事件循環(huán)創(chuàng)建
tasks=asyncio.gather(
asyncio.ensure_future(task1())#ensure_future創(chuàng)建任務
                     )
event_loop.run_until_complete(tasks)
event_loop.close()
print('返回值:',tasks.result())#協(xié)程函數(shù)返回值獲取方法
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

可以發(fā)現(xiàn),對百度發(fā)起進行一次請求耗時0.326s,接下來,在tasks添加10個相同的任務

import aiohttp #支持異步協(xié)程的requests
import asyncio
import time
begin=time.time()
async def task1():
    url = 'https://www.baidu.com/'
    s=aiohttp.ClientSession()#創(chuàng)建會話
    r=await s.get(url)
    html1=await r.text()
    await s.close()#關閉會話
    print(html1)
    return 'task1'
event_loop=asyncio.get_event_loop()#事件循環(huán)創(chuàng)建
tasks=asyncio.gather(
    asyncio.ensure_future(task1()),#ensure_future創(chuàng)建任務
    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

可以發(fā)現(xiàn),時間確實變短了,理論上0.326*10=3.26s,實際耗時0.445s。

拓展:筆者想知道計算機的執(zhí)行速度,1s可以執(zhí)行多少代碼?

分別對單個任務和多個任務進行了十次測試:
單次用時[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,每加一個任務會多執(zhí)行10條代碼,也就是0.074s執(zhí)行了90條代碼,那么一秒鐘可以執(zhí)行多少代碼呢?
1/0.074*90=1216.21622,也就是1216條代碼。可謂是彈指一揮間,代碼已萬行。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容