21

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?

3
  • Which online compiler? Commented Jun 20, 2016 at 6:49
  • 1
    In 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. Commented Jun 20, 2016 at 6:50
  • @Onur codechef.com/ide is one I was looking for compilation. Commented Jun 20, 2016 at 9:28

2 Answers 2

37

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.
Sign up to request clarification or add additional context in comments.

2 Comments

If method create massive amount of temporary objects, simple subtraction may produce irrelevant data. The actual memory consumption depends on gc that clear all redundant objects.
What if garbage collection kicks while executing the function ?
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.