Ganesh S
Ganesh S

Reputation: 317

How to calculate memory usage of a Java program?

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

Answers (2)

Rohit Gupta
Rohit Gupta

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

Amit Bhati
Amit Bhati

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.

  • 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.

Upvotes: 36

Related Questions