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

JMeter中API耗时计算:线程内5个采样首尾总响应时间获取方法

获取JMeter单线程内多个采样的总耗时方法

以下是几种可行的实现方式,按需选择:

方法1:基于采样器自身时间戳计算

这种方式直接利用JMeter采样器的内置时间属性,精准记录第一个采样的开始时间和最后一个采样的结束时间:

  • 在第一个采样器上添加JSR223 PostProcessor,写入Groovy代码:
    // 仅在首次执行时记录开始时间
    if (!vars.get("first_sampler_start")) {
        vars.put("first_sampler_start", ctx.getCurrentSampler().getStartTime().toString())
    }
    
  • 在最后一个采样器上添加JSR223 PostProcessor,写入Groovy代码:
    def lastSamplerEnd = ctx.getCurrentSampler().getEndTime()
    def totalDuration = lastSamplerEnd - Long.parseLong(vars.get("first_sampler_start"))
    vars.put("total_execution_time", totalDuration.toString())
    // 日志输出便于调试
    log.info("从第一个采样开始到最后一个采样结束的总耗时:" + totalDuration + "毫秒")
    
    执行后,可通过${total_execution_time}引用总耗时数值。

方法2:用系统时间戳直接计算

如果不想依赖采样器的内置属性,可通过系统时间戳实现:

  • 在第一个采样器之前添加Test Action元件,给它加JSR223 PreProcessor,写入:
    vars.put("thread_start_time", String.valueOf(System.currentTimeMillis()))
    
  • 在最后一个采样器之后添加Test Action元件,给它加JSR223 PostProcessor,写入:
    def totalDuration = System.currentTimeMillis() - Long.parseLong(vars.get("thread_start_time"))
    vars.put("total_execution_time", totalDuration.toString())
    // 可选:将结果写入本地文件
    new File("execution_log.txt").append("本次线程总耗时:" + totalDuration + "ms\n")
    

方法3:事后查看报表(无需修改脚本)

如果只是需要测试完成后查看结果,可直接用JMeter自带的报表元件:

  • 运行测试后,查看Aggregate Report或Summary Report,找到对应线程组的"Elapsed Time"列,该数值即为线程从启动到结束的总耗时,和第一个采样开始到最后一个采样结束的时间基本一致(若线程组内无额外等待逻辑)。

注意事项

  • 确保所有目标采样器在同一个线程组内,且按预期顺序执行(JMeter默认按元件从上到下执行)
  • 若采样器之间包含逻辑控制器(如If Controller),需确认最终执行的采样数量符合预期,避免时间记录偏差
  • JSR223脚本推荐使用Groovy语言,性能优于BeanShell等其他脚本语言

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:45:28