繁体   English   中英

为什么gevent可以加快下载请求?

[英]Why gevent can speed up requests to download?

我认为requests.get应该是块,所以应该有运行和RUN2之间没有什么区别。

import sys

import gevent
import requests
from gevent import monkey
monkey.patch_all()
def download():
    requests.get('http://www.baidu.com').status_code
def run():
    ls = [gevent.spawn(download) for i in range(100)]
    gevent.joinall(ls)
def run2():
    for i in range(100):
        download()
if __name__ == '__main__':
    from timeit import Timer
    t = Timer(stmt="run();", setup="from __main__ import run")
    print('good', t.timeit(3))
    t = Timer(stmt="run2();", setup="from __main__ import run2")
    print('bad', t.timeit(3))
    sys.exit(0)

但结果是:

good 5.006664161000117
bad 29.077525214999696

那么gevent是否可以加快各种读写速度?

PS:我在mac / python3 / requests 2.10.0 / gevent 1.1.2上运行它

gevent网站

基于libev的快速事件循环(在Linux上为epoll,在FreeBSD上为kqueue)。

基于greenlet的轻量级执行单元。

重复使用Python标准库中的概念的API(例如,有gevent.event.Events和gevent.queue.Queues)。

具有SSL支持的协作套接字

通过线程池或C区执行DNS查询。

猴子修补实用程序,使第三方模块能够合作

基本上,只要for循环一堆requests.get()调用是一个事实,即你,好了,由于缓慢for通过一堆循环requests.get()的调用。 Gevent进行一堆request.get requests.get()调用并不慢,因为您实际上将这些调用扔到了一个线程队列中,然后该队列使用gevent强大的API来高效地运行这些调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM