我正在运行性能测试以获得执行时间和内存使用量。有时(可能是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) + ",");
答案 0 :(得分:1)
当您计算preCacheMemory
时,JVM中可能会有一些garbage
在collected
期间run test
。
run test
中使用的内存少于garbage
。
因此,当您计算postCacheMemory
小于preCacheMemory
并导致负内存使用时。