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

使用K6测试两个URL页面速度并获取各URL独立统计数据的方法

问题根源

你当前的代码全局仅定义了一个Trend类型的sending_recieving_time指标,新旧两个页面的请求耗时都写入同一个指标,统计时自然只能得到所有数据合并后的平均值,无法拆分出单个URL的独立统计结果。

调整方案

推荐通过给指标追加页面标签的方式实现数据拆分,这种方式扩展性更强,后续新增测试页面无需重复定义指标,调整后的逻辑如下:

  1. 保留全局Trend指标定义,在requestPage函数中新增入参标识页面来源
  2. 给指标添加数据时传入标签,标注当前数据属于哪个页面
  3. K6会自动按标签拆分指标统计结果,你可以直接在输出中看到每个页面对应的耗时数据

完整修改后的示例代码

import http from 'k6/http';
import { Trend, check, group } from 'k6';
// 这里替换成你自己的config定义
const config = {
    oldMobileUri: 'www.oldsite.com',
    newMobileUri: 'www.newsite.com'
}

let response;
// 全局指标保留,第二个参数设为true开启标签支持
var sendingRecievingTrend = new Trend("sending_recieving_time", true);

function requestPage(url, pageTag) {
    let response = http.get(url, {
        headers: {
            "Upgrade-Insecure-Requests": "1",
            Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
        }
    });
    
    // 添加数据时传入页面标签
    sendingRecievingTrend.add(response.timings.sending + response.timings.receiving, { page: pageTag });

    check(response, { "Response return 200 HTTP Status Code": r => r.status === 200 });

    return response;
}

group(`Old Mobile Products Page - ${config.oldMobileUri}/products/`, function () {
    // 调用时传入页面标签
    response = requestPage(`${config.oldMobileUri}/products/`, 'old_mobile_products');
});

group(`New Mobile Products Page - ${config.newMobileUri}/products/`, function () {
    response = requestPage(`${config.newMobileUri}/products/`, 'new_mobile_products');
});

结果查看说明

测试执行完成后,在输出的指标中会自动拆分出带标签的统计项:

  • sending_recieving_time{page:old_mobile_products} 对应旧页面的收发耗时统计(包含平均值、p95、p99等所有维度)
  • sending_recieving_time{page:new_mobile_products} 对应新页面的收发耗时统计

如果需要自定义输出格式,也可以在handleSummary函数中按标签提取对应数值,生成自定义的对比报告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:15:09