Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we know memory required in executing an method

Tags:

java

memory

I want to know how much memory is allocated in executing a method ..

Is there any pre-defined method to calculate the memory allocated or any process to calculate ...

Note : Method may contain any number of lines ...

For Example : To calculate time taken to execute method is calcluated by calling System.currentTimeMillis(); before and after calling the particular method . In this way is there any way to calculate memory required

Thank You ...

like image 223
Nimmagadda Gowtham Avatar asked Dec 20 '25 23:12

Nimmagadda Gowtham


2 Answers

You can use a profiler.

They usually offer insights into the heap (and many other interesting things) so you can compare allocations before and after executing a method, which also is the standard approach to finding memory leaks, besides static analysis.

More advanced tools give you more detailed insights and analysis options.

For starters, take a look at visualvm, which comes for free with all current JDKs from Oracle.

like image 186
hiergiltdiestfu Avatar answered Dec 23 '25 13:12

hiergiltdiestfu


You could use Runtime.totalMemory() which (per the Javadoc) returns the total amount of memory in the Java virtual machine.

System.out.println(Runtime.getRuntime().totalMemory());
like image 23
Elliott Frisch Avatar answered Dec 23 '25 11:12

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!