Python_协程_进阶2

从入门到精通,从精通到放弃,今天我们给大家说说放弃协程的原因

本次对协程进行测速,下面有三个实列,分别是:

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容