Reputation: 317
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?
Upvotes: 21
Views: 51623
Reputation: 453
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.
Upvotes: 6
Reputation: 5649
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.
Upvotes: 36