If I use the Runtime
class (freeMemory()
, totalMemory()
, and gc()
), then it gives me memory above MB (i.e. 1,000,000 bytes).
But if I run the same code on any online compiler, then they show memory used in KB (i.e. 1000 bytes). This is a huge difference.
This means Runtime
does not show the actual memory used by the program.
I need to calculate actual memory used by the program. What is the way these online compilers use to calculate memory used by the program?
-
Which online compiler?Onur– Onur2016年06月20日 06:49:58 +00:00Commented Jun 20, 2016 at 6:49
-
1In general: if you need to understand the performance/memory "behavior" of your application, then you need to seriously look into profiling tools. You want to observe over time. Taking one time snapshots using calls like the ones mentioned in your question can only give you very limited information.GhostCat– GhostCat2016年06月20日 06:50:31 +00:00Commented Jun 20, 2016 at 6:50
-
@Onur codechef.com/ide is one I was looking for compilation.Ganesh S– Ganesh S2016年06月20日 09:28:14 +00:00Commented Jun 20, 2016 at 9:28
2 Answers 2
First calculate the memory used before your code execution i.e. first line of your code.
long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
Calculate the memory used after your code execution:-
long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
Then you can do:
long actualMemUsed=afterUsedMem-beforeUsedMem;
It will give you actual memory utilized by your program.
For further memory analysis your best bet is any profiler tool like jvisualvm.
- Do remember it, that Runtime.getRuntime().totalMemory(), this memory is total memory available to your JVM.
- java -Xms512m -Xmx1024m , it means that total memory of your program will start with 512MB, which may lazily loaded to max of 1024MB.
- So if you are running same program, on different JVMs, Runtime.getRuntime().totalMemory() might give you different results.
You can use top command in ubuntu to check % CPU use or % memory use while running the java programme.
top command will give you these many information.
PID
USER
PR
NI
VIRT
RES
SHR
S
%CPU
%MEM
TIME+ COMMAND
just type
top
and hit enter
in your terminal & check java in command section.