一、背景
最近寫文章需要了解和對比一些函數的性能差異,因此在網上找到了一個簡單易用的 Java 性能測試框架 junitperf。
官方介紹它的優勢是:
- 可以和 Junit5 完美契合。
- 使用簡單,便於項目開發過程中的測試實用。
- 提供拓展,用戶可進行自定義開發。
二、范例
2.1 依賴
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.6.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.github.houbb/junitperf --> <dependency> <groupId>com.github.houbb</groupId> <artifactId>junitperf</artifactId> <version>2.0.3</version> </dependency>
大家可以使用本人在剖析《阿里巴巴 Java 開發手冊》專欄中講到的“先猜想后驗證” 的學習方法,這樣印象更深刻,學習效果更好。
通過上圖,我們可以猜測,該框架使用 freemarkder 生成 HTML 報告,使用 commons-math3 進行性能計算,使用 junit-jupiter-engine 支持 Junit 5的特性等。
感興趣大家可以 clone 項目深入研究。
大家還可以通過查看單元測試的方式快速掌握用法:
2.2 示例
使用很簡單,建議直接進入 JunitPerfConfig 直接中看注釋即可明白每個屬性的含義。
希望大家平時學習新技術時,也可以嘗試通過這種方式,快速了解用法。
/** * 執行接口 * 對於每一個測試方法的條件配置 * @author bbhou * @version 1.0.0 * @since 1.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD}) @Documented @API(status = API.Status.MAINTAINED, since = VersionConstant.V2_0_0) @ExtendWith(PerfConfigProvider.class) @TestTemplate public @interface JunitPerfConfig { /** * 執行時使用多少線程執行 * @return int val */ int threads() default 1; /** * 准備時間(單位:毫秒) * @return time in mills */ long warmUp() default 0L; /** * 執行時間。(單位:毫秒) * 默認值:默認為 1min * 這里的執行時間不包含准備時間。 * @return time in mills */ long duration() default 60_000L; /** * 存放統計信息工具 * @return 統計實現類 */ Class<? extends StatisticsCalculator> statistics() default DefaultStatisticsCalculator.class; /** * 存放報告信息類 * @return 報告信息 */ Class<? extends Reporter>[] reporter() default {ConsoleReporter.class}; }
因此隨手寫個示例:
import com.github.houbb.junitperf.core.annotation.JunitPerfConfig; import com.github.houbb.junitperf.core.report.impl.ConsoleReporter; import com.github.houbb.junitperf.core.report.impl.HtmlReporter; import lombok.extern.slf4j.Slf4j; @Slf4j public class PerfTest { @JunitPerfConfig(threads = 10, warmUp = 1_000, duration = 30_000 , reporter = {HtmlReporter.class, ConsoleReporter.class}) public void newStrTestStringBuilder() { StringBuilder stringBuilder = new StringBuilder("demo"); for (int i = 0; i < 100; ++i) { stringBuilder.append(i); } log.info(stringBuilder.toString()); } }
通過 reporter 可以配置 HTML 方式和 控制台方式的報告,下圖為 HTML 方式(在 target 目錄的 junitperf 文件夾對應的包名下):
三、總結
該框架雖然在國內不是特別出名,但是非常簡單易用,對於要求不高的朋友來說已經非常不錯了。
掌握學習的能力,快速上手一個新技術的能力非常重要,希望本文能夠給你帶來一些啟發。
更多詳細內容參見 github 項目說明,更多高級用法可以下載源碼去看下單元測試,也可以根據源碼自行探索。
作者:明明如月
鏈接:https://www.imooc.com/article/302303
來源:慕課網
本文首次發布於慕課網 ,轉載請注明出處,謝謝合作