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的速度,以後有時間再測試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章