一、前言
- 最近測試一個開源項目,發(fā)現(xiàn)生成的
全局id有重復(fù),方法加上 synchronized 提交PR后,有些同行對性能有疑慮,就準備做個 代碼性能測試 - Java基準性能測試 一般用 JMH 比較多,但是 官方建議 性能測試單獨一個項目,感覺麻煩了點
- 后面發(fā)現(xiàn)了 ContiPerf,可以方便的設(shè)置 執(zhí)行次數(shù)、時長、線程數(shù)、預(yù)熱時長,還有 Html格式報告,感覺還比較適合,基于 Junit
二、ContiPerf
1. 安裝
- 有2個倉庫,這里選擇 javatlacati 二開以后的
- 選擇 2.4.3 版本,基于 Junit4,更好的支持 @After
- 另最新 2.4.4-SNAPSHOT 版本,基于Junit5
<dependencies>
<!-- 引入 ContiPerf 測試工具,參考 https://gitee.com/yu120/sequence -->
<dependency>
<groupId>com.github.javatlacati</groupId>
<artifactId>contiperf</artifactId>
<version>2.4.3</version>
<scope>test</scope>
</dependency>
</dependencies>
2. 使用
- 首先,單元測試類 增加屬性 ContiPerfRule
- 測試方法增加 Junit4 的 @Test 注解
- 增加 @PerfTest,配置 invocations 次數(shù),或 duration 毫秒時長,threads 線程數(shù)
- 性能測試嘛,最好配置 預(yù)熱時長 warmUp,單位也是 毫秒
- 多種不同線程數(shù)的測試,可以 多個方法加 @PerfTest 注解哦(這種情況建議把 線程數(shù)加到 測試方法名末尾,線程數(shù)小于 10的 補0,同時測試類增加 @FixMethodOrder(MethodSorters.NAME_ASCENDING),生成的 報告就按 線程數(shù)排序了)
- 還可以配置 @Required 結(jié)果校驗哦,如下示例:每秒吞吐量要 大于等于 100萬
@org.junit.Rule
public ContiPerfRule contiPerfRule = new ContiPerfRule();
@org.junit.Test
@com.github.javatlacati.contiperf.Required(throughput = 100_0000)
@PerfTest(duration = 3300, threads = 4, warmUp = 300)
public void generateId04Threads() {
generateIdThreads();
}
3. 性能測試效果
-
所有的 PerfTest 結(jié)果都輸出到 target/contiperf-report/index.html
ContiPerf.png
4. 示例2:多線程生成id,有無重復(fù)校驗
- ids 要使用 支持并發(fā)的容器,不然多線程 會報錯
- @AfterClass 做結(jié)果校驗
private static final Set<Long> ids = new ConcurrentHashSet<>((int) (INVOCATIONS / 0.7));
@AfterClass
public static void tearDown() {
Assert.assertEquals("generateId duplicated", INVOCATIONS, ids.size());
}
@Test @PerfTest(invocations = INVOCATIONS, threads = 4)
public void generateId() {
ids.add(UniqueIdGenerator.generateId());
}
三、總結(jié)
- ContiPerf,可以方便的設(shè)置 執(zhí)行次數(shù)、時長、線程數(shù)、預(yù)熱時長,還有 Html格式報告,是個比較便捷的 代碼性能測試工具
- 更專業(yè)的 Java 微基準性能測試,也可以考慮 JMH 哦
本文遵守【CC BY-NC】協(xié)議,轉(zhuǎn)載請保留原文出處及本版權(quán)聲明,否則將追究法律責(zé)任。
