Rohit Elayathu
Rohit Elayathu

Reputation: 639

How to find memory used by a function in java

I am calling a function from my code (written in java) and I want to know how much memory that function is using, and do keep in mind that I cannot add any code to the function(which I am calling).

for eg-

 //my code starts
   .
   .
   .
   .
   myfunc();
 //print memory used by myfunc() here
  .
  .
 // my code ends

How to do this?

Upvotes: 5

Views: 2111

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200138

I was successful with this code (it's not guaranteed to work, but try it and there's a good chance it'll give you what you need):

final Runtime rt = Runtime.getRuntime();
for (int i = 0; i < 3; i++) rt.gc();
final long startSize = rt.totalMemory()-rt.freeMemory();
myFunc();
for (int i = 0; i < 3; i++) rt.gc();
System.out.println("Used memory increased by " +
   rt.totalMemory()-rt.freeMemory()-startSize);

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533472

But its wrong, because ideally it should always be zero after subraction.

Actually its right because normally each thread has a TLAB (Thread Local Allocation Buffer) which means it allocates in blocks (so each thread can allocate concurrently)

Turn this off with -XX:-UseTLAB and you will see ever byte allocated.

You should run this multiple times because other things could be running when you use this function.

Upvotes: 0

penartur
penartur

Reputation: 9912

What you're trying to do is basically pointless. There is no such thing as memory used by a function. Your idea of comparing the total memory usage "before" and "after" function call does not have any sense: the function may change global state (which may decrease or increase total memory usage, and in some cases (e.g. cache filling) you probably won't want to consider the increase to count as "memory used by a function), or the garbage collector may run while you're inside of myfunc and decrease the total used memory.

The good question often contains the large part of an answer. What you should do is to correctly ask the question.

Upvotes: 8

Related Questions