You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Locust Web界面展示服务内部计算的延迟统计与图表?

在Locust中实时监控接口内部计算环节的延迟统计

方案1:通过事件钩子+自定义统计条目扩展Locust原生统计

利用Locust的request_success事件钩子,在请求完成后解析响应中的内部计算延迟数据,将其添加到自定义的统计条目里,这些条目会自动同步到Web界面的统计面板中。

代码示例

from locust import HttpUser, task, events
from locust.stats import StatsEntry, stats

# 预定义各内部计算环节的统计条目
internal_compute_stats = {
    "compute_A": StatsEntry(name="compute_A", method="INTERNAL"),
    "compute_B": StatsEntry(name="compute_B", method="INTERNAL"),
    "compute_C": StatsEntry(name="compute_C", method="INTERNAL"),
}

# 将自定义统计条目注册到Locust全局统计中
for entry in internal_compute_stats.values():
    stats.append(entry)

@events.request_success.add_listener
def track_internal_compute_latency(request_type, name, response_time, response_length, response, **kwargs):
    # 仅处理/compute端点的请求结果
    if name != "/compute":
        return
    
    try:
        # 解析响应中的内部延迟数据(假设响应为JSON格式)
        resp_data = response.json()
        # 更新对应计算环节的统计数据
        for compute_name, latency in resp_data.items():
            if compute_name in internal_compute_stats:
                # 确保延迟为毫秒级(Locust默认单位),如果是秒则乘以1000
                internal_compute_stats[compute_name].log(latency, response_length)
    except Exception:
        # 解析失败时忽略,不影响主测试流程
        pass

class ComputeUser(HttpUser):
    @task
    def call_compute_endpoint(self):
        self.client.get("/compute")

配置完成后,Locust Web界面的Statistics面板会新增compute_A、compute_B等条目,实时展示它们的平均延迟、中位数延迟、最大延迟等指标,同时支持查看对应的响应时间分布图表。

方案2:手动上报内部环节延迟数据

如果需要更灵活的控制,可以在任务中手动解析响应数据,通过client.enqueue_request方法将内部计算的延迟数据上报为“虚拟请求”,同样会被Locust统计并展示在Web界面中。

代码示例

from locust import HttpUser, task

class ComputeUser(HttpUser):
    @task
    def call_compute_endpoint(self):
        response = self.client.get("/compute")
        try:
            resp_data = response.json()
            # 遍历各内部计算环节的延迟数据并上报
            for compute_name, latency in resp_data.items():
                # 模拟一个内部请求,上报延迟数据
                self.client.enqueue_request(
                    method="INTERNAL",
                    name=compute_name,
                    response_time=latency,
                    response_length=0,  # 内部计算无响应长度可填0
                )
        except Exception:
            pass

这种方法的优势是无需修改全局事件钩子,直接在任务逻辑中处理,同样能在Web界面实时查看各内部环节的统计数据。

注意事项

  • 确保响应返回的延迟数据单位为毫秒,如果是秒级需乘以1000转换,与Locust默认统计单位保持一致。
  • 两种方案都能复用Locust原生的统计与图表功能,无需额外导出数据后离线计算。

内容的提问来源于stack exchange,提问作者leki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:10:20