简体   繁体   English

挑战:如何使用Python在一秒钟内发送> 1000个HTTP请求

[英]Challenge: How to send > 1000 HTTP requests in one second with Python

Consider the following case: There is a slow server which use about 200ms to handle a request (no including the network transfer time). 请考虑以下情况:有一个慢速服务器使用大约200毫秒来处理请求(不包括网络传输时间)。 And now, we need to send a bunch of requests every second. 现在,我们需要每秒发送一堆请求。

After read this post , I have tried multi-thread, multi-process, twisted (agent.request) and eventlet. 阅读这篇文章后 ,我尝试了多线程,多进程,twisted(agent.request)和eventlet。 But the biggest speedup is only 6x , which is achieved via twisted and eventlet, both are using epoll. 但最大的加速只有6倍 ,这是通过twisted和eventlet实现的,两者都使用了epoll。

The following code shows the test version with eventlet, 以下代码显示了带有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

Anyone could help me to make it clear why the speedup is so low? 任何人都可以帮助我明确为什么加速这么低? And is there any other mechanism could make it much faster? 有没有其他机制可以使它更快?

I know this is an old post but someone might still need this. 我知道这是一个老帖子,但有人可能仍然需要这个。

If you want to do load testing but want to use python then you should use a tool like locust: http://locust.io/ 如果你想进行负载测试但想使用python,那么你应该使用像locust这样的工具: http//locust.io/

Here is my solution which resulted in 10,000 requests in 10 seconds: 这是我的解决方案,在10秒内产生了10,000个请求:

Needed Package: sudo pip install grequests 需要的包: sudo pip install grequests

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

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

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