与 Android OS 类似地对 JVM 内存消耗进行基准测试

Benchmarking JVM memory consumption similarly to how it is done by the Android OS

当尝试对特定方法进行基准测试时,关于在该方法 运行 时创建了多少对象以及它们占用了多少字节,在 Android 中可以这样做:

Debug.resetThreadAllocCount()
Debug.resetThreadAllocSize()
Debug.startAllocCounting()
benchmarkMethod()
Debug.stopAllocCounting()
var memoryAllocCount = Debug.getThreadAllocCount()
var memoryAllocSize = Debug.getThreadAllocSize()

我现在想对相同的方法进行基准测试,但是在普通的桌面应用程序上,这些方法不可用。我没有发现任何类似的东西,而且我尝试过的任何其他内存基准测试代码都没有提供一致的结果,就像上面的代码一样,每次运行相同的基准测试时都会给出完全相同的结果。

任何建议,最好只是代码,我将不胜感激,但是我也愿意尝试一些软件,如果它能够执行我正在尝试做的任务。

ThreadMXBean.getThreadAllocatedBytes 可以帮助:

com.sun.management.ThreadMXBean bean =
        (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long currentThreadId = Thread.currentThread().getId();

long before = bean.getThreadAllocatedBytes(currentThreadId);
allocatingMethod();
long after = bean.getThreadAllocatedBytes(currentThreadId);

System.out.println("Allocated " + (after - before) + " bytes");

方法returns总分配内存的近似值,但这种近似值通常非常精确。

另外,async-profiler 有 Java API 用于分析分配。它不仅计算分配了多少个对象,而且还显示了确切的分配对象以及分配站点的堆栈跟踪。

public static void main(String[] args) throws Exception {
    AsyncProfiler profiler = AsyncProfiler.getInstance();

    // Dry run to skip allocations caused by AsyncProfiler initialization
    profiler.start("alloc", 0);
    profiler.stop();

    // Real profiling session
    profiler.start("alloc", 0);

    allocatingMethod();

    profiler.stop();
    profiler.execute("file=alloc.svg");  // save the output to alloc.svg
}

如何运行:

java -Djava.library.path=/path/to/async-profiler -XX:+UseG1GC -XX:-UseTLAB Main
需要

-XX:+UseG1GC -XX:-UseTLAB 选项来记录 all 分配。否则,async-profiler 将以采样模式工作,仅记录一小部分分配。

输出结果如下: