0

I'm running performance tests to get execution time and memory usage. Sometimes (maybe twice or thrice out of 30) negative memory usage is reported. I would like to use Runtime so the console output has comma separated data that is easy to copy and paste into Excel.

Why do I get negative memory usage when I run a performance test?

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) + ",");
Erik
  • 503
  • 1
  • 7
  • 26

1 Answers1

1

When you calculate preCacheMemory, there might be some garbage in JVM which will be collected during run test.

The memory used in run test is less than these garbage.

So, when you calculate postCacheMemory is less than preCacheMemory and leads to negative memory usage.

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Do you know if there's a way to clear the garbage? System.gc() isn't guaranteed. – Erik May 04 '18 at 14:29
  • 1
    @Erik This may help https://stackoverflow.com/questions/1481178/how-to-force-garbage-collection-in-java – xingbin May 04 '18 at 14:31