挑战:如何使用 Python 一秒内发送超过 1000 个 HTTP 请求

2023-12-15

考虑以下情况:有一个缓慢的服务器,使用大约200ms处理请求(不包括网络传输时间)。现在,我们需要每秒发送一堆请求。

读完这篇文章后post,我尝试过多线程、多进程、twisted(agent.request)和eventlet。但最大的加速只是6x,这是通过twisted和eventlet实现的,两者都是使用epoll。

以下代码显示了带有 eventlet 的测试版本,

import eventlet
eventlet.monkey_patch(all=False, socket=True)

import requests

def send():
    pile = eventlet.GreenPile(30)
    for i in range(1000):
        pile.spawn(requests.get, 'https://api.???.com/', timeout=1)
    for response in pile:
        if response:
            print response.elapsed, response.text

任何人都可以帮助我弄清楚为什么加速如此之低?还有其他机制可以让它更快吗?


我知道这是一篇旧文章,但有人可能仍然需要它。

如果你想做负载测试但想使用 python 那么你应该使用像 locust 这样的工具:http://locust.io/

这是我的解决方案,它在 10 秒内产生了 10,000 个请求:

需要的包:sudo pip install 请求

Code:

import grequests
import time

start_time = time.time()
# Create a 10000 requests
urls = ['http://www.google.co.il']*10000
rs = (grequests.head(u) for u in urls)

# Send them.
grequests.map(rs)

print time.time() - start_time # Result was: 9.66666889191
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

挑战:如何使用 Python 一秒内发送超过 1000 个 HTTP 请求 的相关文章

随机推荐