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) + ",");