报告 JMH 基准测试的最大堆大小

Report maxmium heap size for JMH benchmarks

我正在使用 Java 测量工具 (JMH) 对一些例程进行基准测试。我有兴趣获得每个 运行 的最大堆大小。 JMH 的 GC Profiler 为我提供了分配率和流失率等信息,但我正在寻找测试期间获得的最大堆 运行。这可以做到吗?

您可以实现自己的探查器:

public class MaxMemoryProfiler implements InternalProfiler {

    @Override
    public String getDescription() {
        return "Max memory heap profiler";
    }

    @Override
    public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) {

    }

    @Override
    public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams,
        IterationResult result) {

        long totalHeap = Runtime.getRuntime().totalMemory(); // Here the value
                                                         // you want to
                                                         // collect

        Collection<ScalarResult> results = new ArrayList<>();
        results.add(new ScalarResult("Max memory heap", totalHeap, "bytes", AggregationPolicy.MAX));

        return results;
    }
}

并将其添加到您的 OptionsBuilder:

    OptionsBuilder()
         /* options ... */               
        .addProfiler(MaxMemoryProfiler.class);

将选项AggregationPolicy.MAX添加到ScalarResult,输出将是执行的每个基准测试的最大结果。

顺便说一句,如果你想用内存做指标,一篇你可以阅读的好文章是https://cruftex.net/2017/03/28/The-6-Memory-Metrics-You-Should-Track-in-Your-Java-Benchmarks.html