private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) throws Exception {
runGC();
long start = usedMemory();
// Do Something ...
long used = usedMemory() - start;
System.out.println("Used memory is bytes: " + used);
System.out.println("Used memory is megabytes: " + bytesToMegabytes(used));
}
private static final Runtime s_runtime = Runtime.getRuntime();
private static long usedMemory() {
return s_runtime.totalMemory() - s_runtime.freeMemory();
}
private static void runGC() throws Exception {
long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
s_runtime.runFinalization();
s_runtime.gc();
Thread.currentThread().yield();
usedMem2 = usedMem1;
usedMem1 = usedMemory();
}
}
2017年12月4日 星期一
計算佔用記憶體
標籤:
JAVA
訂閱:
文章 (Atom)