如何测量 Python 请求 POST 请求的服务器响应时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43252542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:42:40  来源:igfitidea点击:

How to measure server response time for Python requests POST-request?

pythonpython-3.xservernetwork-programmingpython-requests

提问by Shuzheng

I create requestsPOST-requests like this, where I specify timeout threshold:

我创建这样的requestsPOST 请求,在其中指定超时阈值:

response = requests.post(url, data=post_fields, timeout=timeout)

response = requests.post(url, data=post_fields, timeout=timeout)

However, to determine a "good" threshold value, I would like to benchmark the server response time in advance.

但是,要确定“良好”阈值,我想提前对服务器响应时间进行基准测试。

How do I compute the minimum and maximum response times for the server?

如何计算服务器的最小和最大响应时间?

回答by Nicolas Lykke Iversen

The Responseobject as returned by requests.post()has a property called elapsed, which give the time delta between the Requestwas sent and the Responsewas received. To get the delta in seconds, use the total_seconds()method:

Response返回的对象requests.post()有一个名为 的属性elapsed,它给出了Request发送和Response接收之间的时间增量。要以秒为单位获取增量,请使用以下total_seconds()方法:

response = requests.post(url, data=post_fields, timeout=timeout)
print(response.elapsed.total_seconds())

It should be mentioned that requests.post()is a synchronous operation, which means that it "blocks" until the response is received.

应该提到的requests.post()是,这是一个同步操作,这意味着它“阻塞”直到收到响应。

回答by Daniel Scott

It depends on whether you can hit the server with a lot of test requests, or whether you need to wait for real requests to occur.

这取决于您是否可以通过大量测试请求来访问服务器,或者您是否需要等待真正的请求发生。

If you need real request data, then you'd need to wrap the call to determine the time of each request:

如果您需要真实的请求数据,那么您需要包装调用以确定每个请求的时间:

start = time.clock()
response = requests.post(url, data=post_fields, timeout=timeout)
request_time = time.clock() - start
self.logger.info("Request completed in {0:.0f}ms".format(request_time)
#store request_time in persistent data store

You'd need somewhere to store the results of each request over a period of time (file, database, etc). Then you can just calculate the stats of the response times.

您需要在某个地方存储一段时间内每个请求的结果(文件、数据库等)。然后你可以计算响应时间的统计数据。

If you have a test server available, you could benchmark the response without python using something like apachebench and sending test data for each request:

如果您有可用的测试服务器,则可以使用 apachebench 之类的工具在没有 python 的情况下对响应进行基准测试,并为每个请求发送测试数据:

https://gist.github.com/kelvinn/6a1c51b8976acf25bd78

https://gist.github.com/kelvinn/6a1c51b8976acf25bd78