Java系列-性能工具junitpref使用
2025年9月13日大约 2 分钟
Java系列-性能工具junitpref使用
项目依赖
- jdk
jdk1.8 及其以上版本
- junit
Junit5 及其以上版本
POM 引入
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>junitperf</artifactId>
<version>2.0.0</version>
</dependency>
配置说明
测试注解指定
@JunitPerfConfig
指定测试时的属性配置。(必填项)
属性 | 说明 | 类型 | 默认值 | 备注 |
---|---|---|---|---|
threads | 执行时使用多少线程执行 | int | 1 | |
warmUp | 准备时间 | long | 0 | 单位:毫秒 |
duration | 执行时间 | long | 60_000(1分钟) | 单位:毫秒 |
statistics | 统计实现 | StatisticsCalculator | DefaultStatisticsCalculator | |
reporter | 报告实现 | Reporter | ConsoleReporter |
使用如下:
public class JunitPerfConfigTest {
/**
* 2个线程运行。
* 准备时间:1000ms
* 运行时间: 2000ms
* @throws InterruptedException if any
*/
@JunitPerfConfig(threads = 2, warmUp = 1000, duration = 2000)
public void junitPerfConfigTest() throws InterruptedException {
System.out.println("junitPerfConfigTest");
Thread.sleep(200);
}
}
各种报告的实现
这里主要是对于性能测试统计的输出方式。 支持以下方式:
方式 | 案例 |
---|---|
默认方式 | DefaultReporterTest |
命令行 | ConsoleReporterTest |
HTML | HtmlReporterTest |
组合方式 | MultiReporterTest |
自定义方式 | DefineReporterTest |
@JunitPerfRequire
指定测试时需要达到的要求。(选填项)
属性 | 说明 | 类型 | 默认值 | 备注 |
---|---|---|---|---|
min | 最佳的运行耗时 | float | -1 | 最快的运行耗时如果高于这个值,则视为失败。单位:毫秒 |
max | 平均的运行耗时 | float | -1 | 最坏的运行耗时如果高于这个值,则视为失败。单位:毫秒 |
average | 平均的运行耗时 | float | -1 | 平均的运行耗时如果高于这个值,则视为失败。单位:毫秒 |
timesPerSecond | 每秒的最小执行次数 | int | 0 | 如果低于这个最小执行次数,则视为失败。 |
percentiles | 对于执行耗时的限定 | String[] | {} | percentiles={"20:220", "30:250"}。20% 的数据执行耗时不得超过 220ms;30% 的数据执行耗时不得超过 250ms; |
使用如下:
public class JunitPerfRequireTest {
/**
* 配置:2个线程运行。准备时间:1000ms。运行时间: 2000ms。
* 要求:最快不可低于 210ms, 最慢不得低于 250ms, 平均不得低于 225ms, 每秒运行次数不得低于 4 次。
* 20% 的数据不低于 220ms, 50% 的数据不得低于 230ms;
*
* @throws InterruptedException if any
*/
@JunitPerfConfig(threads = 2, warmUp = 1000, duration = 2000)
@JunitPerfRequire(min = 210, max = 250, average = 225, timesPerSecond = 4, percentiles = {"20:220", "50:230"})
public void junitPerfConfigTest() throws InterruptedException {
System.out.println("junitPerfConfigTest");
Thread.sleep(200);
}
}
报告方式
命令行方式
大致如下:
[INFO] 2018-01-14 22:16:31.419 [] - Started at: 2018-01-14 22:16:30.194
[INFO] 2018-01-14 22:16:31.419 [] - Invocations: 10
[INFO] 2018-01-14 22:16:31.420 [] - Success: 10
[INFO] 2018-01-14 22:16:31.420 [] - Errors: 0
[INFO] 2018-01-14 22:16:31.420 [] - Thread Count: 2
[INFO] 2018-01-14 22:16:31.421 [] - Warm up: 0ms
[INFO] 2018-01-14 22:16:31.421 [] - Execution time: 1000ms
[INFO] 2018-01-14 22:16:31.421 [] - Throughput: 10/s (Required: -1/s) - PASSED
[INFO] 2018-01-14 22:16:31.424 [] - Min latency: 200.2112ms (Required: -1.0ms) - PASSED
[INFO] 2018-01-14 22:16:31.424 [] - Max latency: 205.67862ms (Required: -1.0ms) - PASSED
[INFO] 2018-01-14 22:16:31.425 [] - Ave latency: 202.97829ms (Required: -1.0ms) - PASSED
HTML 方式
页面如下: