I am made a program which uses A* search algorithm to solve 8 game puzzle. I was interested in seeing how much memory is being used by my program from start to finish.
So far i have done
In the beginning of the program
static double totalMem = Runtime.getRuntime().totalMemory()/(1024*1024);
static double memoryMax = Runtime.getRuntime().maxMemory()/(1024*1024);
and at the end of the program
timeTaken-=System.currentTimeMillis();
System.out.println("\n\n-------Total Time Taken = "+Math.abs(timeTaken)+
" millisec ------\n ");
System.out.println("-------Maximum Memory = "+memoryMax+" MB------\n ");
System.out.println("-------Total Memory = "+totalMem
+" MB------\n ");
currMem = Runtime.getRuntime().freeMemory()/(1024*1024);
System.out.println("-------Free Memory = "+currMem+" MB------\n ");
double memUsed = (Runtime.getRuntime().totalMemory())/(1024*1024)-currMem;
System.out.println("-------Total Used = "+memUsed
+" MB------\n ");
This doesn't seems to be right. When i test with different sets of data. Any sugessitions
It would be better to use profiler or similar software for this purpose. You can start with jvisualvm which is included in JDK or JProfiler.
The problem looks related to the thread-local allocation buffer.
The objects might be getting created on TLAB.
Read this: https://blogs.oracle.com/jonthecollector/entry/the_real_thing
So everytime you run the program, it will show similar values.
Run the program by switching off this feature, pass below in VM arguments:-
-XX:-UseTLAB
You can also use "Java Mission Control" (newer version of JVisualVM), that allows you to make snapshots of your memory. Add this parameters at startup of your programm:
-XX:+UnlockCommercialFeatures
-XX:+FlightRecorder
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=true
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Its in the "bin" folder of your JDK 7 too, called: "jmc.exe"
Runtime works correctly. You could take the difference before executing the logic and after to see how much memory used. A quick sample
import java.util.ArrayList;
import java.util.List;
public class MemoryTest {
private static final int KB = 1024;
public static void main(String[] args) {
long initialMemory = getUsedMemory();
List<String> dummy = new ArrayList<String>();
for(int i=0; i<10000; i++){
dummy.add("Dummy " + i);
}
System.out.println("Total used by program = " + (getUsedMemory() - initialMemory) + " KB");
}
private static long getUsedMemory() {
Runtime runtime = Runtime.getRuntime();
return (runtime.totalMemory() - runtime.freeMemory()) / KB;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.