python - 在 python 3 中获取 REST API 服务器响应时间
问题描述
我正在尝试在 python 3 中获取服务器响应时间
我试过这段代码 -
api_url = "https://example.com?id=12345"
api_header = {'Authorization': 'Bearer ' + access_token}
api_response = requests.get(api_url, headers=api_header)
response_time = api_response.elapsed
print(response_time)
但它返回的“经过时间”远高于服务器响应时间。
当我从 Postman 查询相同的 api 时,它显示的响应时间约为 250 毫秒。但是上面的代码显示了850ms的经过时间。
有没有办法在 python 3 中获得实际的服务器响应时间?
解决方案
您可以尝试使用该datetime
模块。通过将之前和之后的时间存储为变量,您可以计算出它们之间的差异,从而计算出进行调用所花费的时间。
import datetime as dt
api_url = "https://example.com?id=12345"
api_header = {'Authorization': 'Bearer ' + access_token}
start = dt.datetime.now()
api_response = requests.get(api_url, headers=api_header)
end = dt.datetime.now()
time_delta = end - start
response_time = time_delta.total_seconds()
print(response_time)
如果这不能满足您的要求,我建议您查看timeit模块。
推荐阅读
- javascript - 当 pub.dev 插件不支持 web 时,使用 npm 包进行 Flutter web
- javascript - RegEx Javascript - 整个字符串中只有 0-2 个空格或连字符?
- java - 如何解决 java.lang.NoSuchFieldError: RETURN_NULL_AND_BLANK in java
- python - Python:如何实现具有顺序执行的异步调度程序?
- node.js - 使用 SSH 连接 MongoDB Atlas 失败
- python - 在 pandas 数据框中对多行进行分组(文本、日期时间和 int 类型的数据)
- reactjs - 使用 Bootstrap 4.5.2 反应身体 Css
- javascript - 谁能解释一下这在 XML 中的含义?
- visual-studio-code - 在 vscode 扩展上添加文档符号层次结构
- reactjs - 离子标签即使在空白页上也没有出现/发挥应有的作用