LoginSignup
2
3

More than 1 year has passed since last update.

Javaでヒープサイズ測定 JUnit5編

Last updated at Posted at 2021-12-21

Javaのカレンダー | Advent Calendar 2021の13日目の記事です

概要

Javaの単体テストでヒープ(メモリ)を簡単に測定したいときに使える方法

参考

やり方

正直、以下のページを見たまんま

JUnit 5・quick-perf / doc Wiki

測定コード

ドキュメントに JUnit 5 >= 5.6.0 is required とあったので注意

これをもってきました

quickperf-examples/JvmAnnotationsJunit5Test.java at master · quick-perf/quickperf-examples

@QuickPerfTest
public class SampleQuickPerfTest {
    @MeasureHeapAllocation
    @Test
    void test() {
        new ArrayList<>(100);
    }
}

実行結果

[QUICK PERF] Measured heap allocation (test method thread): 440 bytes

pom.xml の設定

以下の依存を追加

dependencyManagement で bom を指定しておけば、dependencies の version が統一される程度のもので、
dependencies で を指定しても動きはしました

pom.xml
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>5.7.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.quickperf</groupId>
            <artifactId>quick-perf-bom</artifactId>
            <version>1.1.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

...

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.quickperf</groupId>
        <artifactId>quick-perf-junit5</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

付録

この Quick Perf には他にも面白い機能(アノテーション)があって、参考の動画などをみて感覚を掴みつつ、どういうシチュエーションで利用するかは謎だが興味深いテストができそう

JVM annotations · quick-perf/doc Wiki

  • @HeepSize, @Xmx (@Xms) : ヒープサイズの最大値を設定できる
  • @UseGC : GC の種類が指定できる
  • @ExpectNoHeapAllocation : ヒープを確保しないことをチェックする
  • @ProfileJvm : JDK Flight Recorder のプロファイルが取れる(pom.xml に quick-perf-jfr-annotations の依存の追加が必要)

また、これとは別に JPA の 発行SQLの回数などをアサーションできるアノテーションもある

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3