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

K6中如何获取每个API请求的单独执行耗时统计?

K6 单API请求执行耗时明细获取方案

K6原生支持获取每个HTTP请求的全阶段耗时明细,且对应逻辑完全不会干扰你原有的链式API调用顺序,不会影响前序接口响应作为后序请求参数的逻辑。

内置耗时字段说明

K6 发起HTTP请求后返回的Response对象的timings属性自带所有阶段耗时数据,单位均为毫秒,常用字段如下:

  • duration:请求全链路总耗时,从请求发起至响应体完全接收完成的总时长
  • connecting:TCP连接建立阶段耗时
  • tls_handshaking:TLS握手阶段耗时
  • sending:请求体发送阶段耗时
  • waiting:TTFB(首字节响应时间),即请求发送完成到收到第一个响应字节的等待耗时
  • receiving:响应体接收阶段耗时
  • blocked:请求等待空闲连接的排队耗时

链式调用场景下的使用示例

你可以在每个请求结束后直接读取耗时数据,再执行后续依赖该请求响应的接口调用,完全不打乱原有执行顺序:

import http from 'k6/http';
import { check } from 'k6';

export default function () {
  // 调用第一个接口
  const createOrderResp = http.post(
    'https://example.com/api/order',
    JSON.stringify({ goods_id: 123 }),
    { headers: { 'Content-Type': 'application/json' } }
  );
  check(createOrderResp, { '创建订单成功': (r) => r.status === 200 });

  // 直接读取第一个接口的耗时明细,可按需打印或存储
  console.log(`创建订单接口总耗时:${createOrderResp.timings.duration}ms`);
  console.log(`创建订单接口TTFB:${createOrderResp.timings.waiting}ms`);

  // 用第一个接口返回的订单ID调用第二个查询接口,不影响原有逻辑
  const orderId = createOrderResp.json('data.order_id');
  const queryOrderResp = http.get(`https://example.com/api/order/${orderId}`);
  check(queryOrderResp, { '查询订单成功': (r) => r.status === 200 });

  // 读取第二个接口的耗时明细
  console.log(`查询订单接口总耗时:${queryOrderResp.timings.duration}ms`);
}

批量聚合统计配置

如果需要测试结束后统一查看所有接口的耗时统计(平均值、p95、p99等分位值),可以给每个请求添加name标签,K6会自动按标签分组统计:

const createOrderResp = http.post(
  'https://example.com/api/order',
  JSON.stringify({ goods_id: 123 }),
  {
    headers: { 'Content-Type': 'application/json' },
    tags: { name: '创建订单接口' } // 给接口打标签
  }
);

const queryOrderResp = http.get(`https://example.com/api/order/${orderId}`, {
  tags: { name: '查询订单接口' }
});

测试结束后,K6的默认报告中会按每个标签单独展示对应接口的所有耗时统计数据,无需手动聚合。

自定义指标存储(可选)

如果需要对耗时数据做自定义分析,可以将耗时写入K6的Trend指标:

import http from 'k6/http';
import { Trend } from 'k6/metrics';

// 声明自定义耗时指标
const createOrderDuration = new Trend('create_order_total_duration');
const queryOrderTTFB = new Trend('query_order_ttfb');

export default function () {
  const createOrderResp = http.post(
    'https://example.com/api/order',
    JSON.stringify({ goods_id: 123 }),
    { headers: { 'Content-Type': 'application/json' } }
  );
  // 写入指标
  createOrderDuration.add(createOrderResp.timings.duration);

  const orderId = createOrderResp.json('data.order_id');
  const queryOrderResp = http.get(`https://example.com/api/order/${orderId}`);
  queryOrderTTFB.add(queryOrderResp.timings.waiting);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:06:03