运行时报告负内存使用情况

时间:2018-05-04 14:16:25

标签: java

我正在运行性能测试以获得执行时间和内存使用量。有时(可能是30次中的两次或三次)报告负内存使用情况。我想使用Runtime,因此控制台输出具有逗号分隔的数据,易于复制和粘贴到Excel中。

为什么在运行性能测试时会出现负内存使用情况?

Runtime runtime = Runtime.getRuntime();
long preCacheMemory = runtime.totalMemory() - runtime.freeMemory();
start = System.nanoTime();

// run test

long elapsedCacheBuildTime = System.nanoTime() - start;
long postCacheMemory = runtime.totalMemory() - runtime.freeMemory();
System.out.print("Cache mem (bytes) = " + (postCacheMemory - preCacheMemory) + ",");
System.out.print("Cache Build Time = " + TimeUnit.NANOSECONDS.toMicros(elapsedCacheBuildTime) + ",");

1 个答案:

答案 0 :(得分:1)

当您计算preCacheMemory时,JVM中可能会有一些garbagecollected期间run test

run test中使用的内存少于garbage

因此,当您计算postCacheMemory小于preCacheMemory并导致负内存使用时。