如何在Locust中获取特定请求的响应时间统计数据?
获取特定请求的响应时间统计(非聚合结果)
完全不需要依赖CSV输出,直接通过Locust的请求统计对象就能获取特定请求的平均、中位数、百分位响应时间,具体操作如下:
定位特定请求的统计实例
用请求的名称和方法来精准获取对应统计对象,代码示例:request_stats = self.environment.stats.requests.get(name="你的请求名称", method="GET")注意这里的
name要和你定义请求时传入的name参数一致(比如self.client.get("/api", name="api_get")里的api_get),method对应请求的HTTP方法(GET/POST等)。获取各类响应时间统计值
拿到特定请求的统计实例后,直接调用对应的属性或方法即可:- 平均响应时间:
request_stats.avg_response_time - 中位数响应时间:
request_stats.median_response_time - 百分位响应时间:
request_stats.get_response_time_percentile(0.95)(替换0.95为你需要的百分位数值)
- 平均响应时间:
完整使用示例
可以在任务逻辑中实时获取,也可以在测试结束时批量导出:
from locust import task, HttpUser, events class TestUser(HttpUser): @task def target_request(self): # 发起请求时指定名称,方便后续定位统计 self.client.get("/user/profile", name="user_profile_get") # 获取该请求的统计数据 req_stats = self.environment.stats.requests.get(name="user_profile_get", method="GET") if req_stats: print(f"【user_profile_get】平均响应时间: {req_stats.avg_response_time}ms") print(f"【user_profile_get】中位数响应时间: {req_stats.median_response_time}ms") print(f"【user_profile_get】95%百分位响应时间: {req_stats.get_response_time_percentile(0.95)}ms") # 测试结束时批量输出所有请求的统计 @events.test_stop.add_listener def print_all_request_stats(environment, **kwargs): print("\n=== 所有请求统计结果 ===") for stats in environment.stats.requests.values(): print(f"\n请求: {stats.method} {stats.name}") print(f"平均响应时间: {stats.avg_response_time}ms") print(f"中位数响应时间: {stats.median_response_time}ms") print(f"90%百分位响应时间: {stats.get_response_time_percentile(0.90)}ms") print(f"99%百分位响应时间: {stats.get_response_time_percentile(0.99)}ms")
这些统计值是Locust实时计算维护的,你可以根据需求将其输出到日志、控制台,或者写入自定义格式的文件,完全不需要依赖CSV导出。
内容的提问来源于stack exchange,提问作者Barak Bensimhon
相关产品推荐
相关产品推荐

