获取 HTTP 请求从发送到接收响应所花费的总时间 - 详解

response.elapsed.total_seconds() 是 Python requests 库中的一个方法,用于获取 HTTP 请求从发送到接收响应所花费的总时间(以秒为单位,浮点数形式)。以下是具体用法和示例:


基本用法

import requests response = requests.get("https://www.example.com")elapsed_time = response.elapsed.total_seconds()  # 获取请求耗时(秒)print(f"请求耗时: {elapsed_time} 秒")

完整示例

1. 测量请求耗时并处理超时

import requests url = "https://www.example.com"try:    response = requests.get(url, timeout=5)  # 设置超时时间为5秒    elapsed = response.elapsed.total_seconds()    print(f"请求成功!状态码: {response.status_code}, 耗时: {elapsed:.3f} 秒")except requests.exceptions.Timeout:    print("请求超时!")except requests.exceptions.RequestException as e:    print(f"请求失败: {e}")

2. 比较多个请求的耗时

import requests urls = [    "https://www.google.com",    "https://www.github.com",    "https://www.python.org"] for url in urls:    try:        response = requests.get(url)        elapsed = response.elapsed.total_seconds()        print(f"{url} 耗时: {elapsed:.2f} 秒")    except Exception as e:        print(f"{url} 请求出错: {e}")

3. 结合性能测试(计算平均耗时)

import requestsimport statistics url = "https://www.example.com"times = [] for _ in range(5):  # 发送5次请求,计算平均耗时    response = requests.get(url)    times.append(response.elapsed.total_seconds()) avg_time = statistics.mean(times)print(f"平均耗时: {avg_time:.3f} 秒")

关键说明

  1. ​**response.elapsed**​ 是一个 datetime.timedelta 对象,total_seconds() 将其转换为秒。
  2. 适用场景​:性能监控、API响应时间分析、超时处理等。
  3. 注意事项​:
    • 如果请求失败(如超时或网络错误),response 对象可能不存在,需配合异常处理使用。
    • 时间不包括DNS解析、TCP连接等底层网络开销,仅测量从发送请求到接收第一个字节的时间。

输出示例

请求成功!状态码: 200, 耗时: 0.452 秒https://www.google.com 耗时: 0.32 秒https://www.github.com 耗时: 0.87 秒平均耗时: 0.512 秒

通过这种方法,你可以方便地监控和优化请求性能。

 

posted @ 2025-07-20 15:25  wzzkaifa  阅读(100)  评论(0)    收藏  举报