Java代碼性能測試實戰(zhàn)之ContiPerf安裝使用
更新時間:2023年06月26日 11:25:00 作者:javalover123
這篇文章主要為大家介紹了Java代碼性能測試實戰(zhàn)之ContiPerf安裝使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
一、前言
- 最近測試一個開源項目,發(fā)現(xiàn)生成的
全局id有重復,方法加上 synchronized 提交PR后,有些同行對性能有疑慮,就準備做個 代碼性能測試 - Java基準性能測試 一般用 JMH 比較多,但是 官方建議 性能測試單獨一個項目,感覺麻煩了點
- 后面發(fā)現(xiàn)了 ContiPerf,可以方便的設(shè)置 執(zhí)行次數(shù)、時長、線程數(shù)、預熱時長,還有 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ù)
- 性能測試嘛,最好配置 預熱時長 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

4. 多線程生成id,有無重復校驗
- 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ù)、預熱時長,還有 Html格式報告,是個比較便捷的 代碼性能測試工具
更專業(yè)的 Java 微基準性能測試,也可以考慮 JMH 哦
以上就是Java代碼性能測試實戰(zhàn)之ContiPerf安裝使用的詳細內(nèi)容,更多關(guān)于Java性能測試ContiPerf的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Springboot整合xxl-job實現(xiàn)動態(tài)傳參
XXL-JOB是一個分布式任務(wù)調(diào)度平臺,本文主要介紹了Springboot整合xxl-job實現(xiàn)動態(tài)傳參,具有一定的參考價值,感興趣的可以了解一下2025-03-03
SpringBoot中使用Redis對接口進行限流的實現(xiàn)
本文將結(jié)合實例代碼,介紹SpringBoot中使用Redis對接口進行限流的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07

