Python requests及aiohttp速度对比代码实例

这篇文章主要介绍了Python requests及aiohttp速度对比代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

环境:centos7 python3.6

测试网址:www.bai.com

测试方式:抓取百度100次

结果:

aio: 10.702147483825684s
requests: 12.404678583145142s

异步框架的速度还是有显著提升的。

下面贡献代码:

 import aiohttp import time import requests import asyncio def test_requests(): """ 测试requessts请求百度100次时间 """ start = time.time() url = "https://www.baidu.com" for i in range(100): requests.get(url) end = time.time() print("requests:") print( end - start ) async def aio_download(url): """ aiohttp 下载 """ async with aiohttp.ClientSession() as session: await session.get(url) async def test_aio(): """ 测试aiohtpp请求百度100次时间 """ url = "https://www.baidu.com" start = time.time() for i in range(100): await aio_download(url) end = time.time() print("aio: ") print( end - start ) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(test_aio()) test_requests()

――――――――――――――――――――――――――――――――――――――――

-―――――――――――――――――――――――――――――――――――――――――

小贴士:

requests不要使用session进行反复抓取一个网站的测试,因为从第2次开始,读取的就是缓存了,无论抓取50次还是100次或是更多,总时间都是1s以内。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持html中文网。

以上就是Python requests及aiohttp速度对比代码实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python