Grequests VS aiohttp+asyncio

1. grequests

  • 什么是grequests
    grequests 是基于 requestsgevent 的一个第三方库,详细使用请见 github 地址 ,和aiohttp相同的是,同样是使用的纯协程

  • 使用 grequests 获取 51wady.com 的电影列表。源码获得后,此处不在分析源码,只获取这个页面的字符数,代码如下:

import grequests,time

nowtime=time.time()
url="http://www.51wady.com/page/{}"
tasks=(grequests.get(url.format(i)) for i in range(1,101))
def exception_handler(request, exception):
    print("request failed")
gr=grequests.imap(tasks, exception_handler=exception_handler)
print([len(i.text) for i in gr],time.time()-nowtime)
# 输出结果
[48319, 52304, 47983, 47613, 48540, 48124, 47897, 48431, 47629, 47326, 47387, 46
819, 46266, 47350, 46703, 47402, 47118, 47657, 47394, 47173, 47234, 47523, 47003
, 46918, 46793, 47095, 46809, 47084, 47590, 46947, 46991, 47058, 46707, 46708, 4
6717, 46800, 47628, 47301, 46864, 47752, 47172, 47210, 47504, 47612, 47543, 4660
1, 46586, 46664, 47723, 47021, 46511, 46340, 47309, 47376, 46723, 46556, 47708,
46923, 47647, 46567, 46942, 46699, 46907, 46899, 47899, 47173, 47020, 46592, 469
27, 47155, 47596, 46920, 46869, 47511, 47172, 46820, 47316, 47275, 46585, 46740,
 47144, 46830, 46842, 47106, 46963, 47357, 46710, 46289, 46827, 46531, 46786, 46
951, 47746, 46966, 46486, 46664, 46770, 46539, 47149, 47254] 12.740842819213867

amazing! 令人惊喜的是,0出错。这个速度挺不错,12.74s,我觉得再配合多进程,可以说是非常牛了。
不过有一点要指出的是,grequests的map方法和imap方法的速度真是相差甚远,由于map返回的是一个tasks任务顺序返回的列表,而imap是返回的一个生成器,并且不按顺序,所以后者的速度要快不止10倍的速度,而且map易出现超时等错误,所以推荐用imap方法。

2.aiohttp+asyncio

    pip install ahttp
  • 现在进行同样的100次请求
import ahttp, time

start=time.time()
tasks=(ahttp.get("http://www.51wady.com/page/{}".format(i)) for i in range(1,101))
result=ahttp.map(tasks)
print([len(i) for i in result],time.time()-start)
结果:13.01383113861084

两者的速度可谓是不相上下,毕竟都是用的协程。只能说是异曲同工吧,但其实这个测试不是公平的,因为grequests默认是开启session的,而且好像不能关掉。
ahttp默认关闭session, 具体开启session的速度,以后有时间再测试。

猜你喜欢

转载自blog.csdn.net/getcomputerstyle/article/details/78446892