btrace test the memory used by calling a function

274 Views Asked by At

Using btrace, I want to test how much heap my function used, so I write:

enter image description here

Above the code is samples of btrace I used.

And operating my function twice I got two different results:

enter image description here

As the pic shows, the heaps cost differs:one is as much as twice as another one.

1

There are 1 best solutions below

0
On

You can not tell how much memory is needed by a certain method by diffing the JVM heap usage before and after the method has been invoked. Too many things go on in the system while the method is executing and the numbers you are obtaining represent the memory allocated by the JVM from OS - the results will tell you nothing.

If you want something at least remotely usable you should take a heap dump before and after the method invocation (Sys.Memory.dumpHeap(fileName)) and use a heapwalker to diff those two. Still, you will get quite a lot of noise there but it is much better than relying on the memory allocated by OS.

The most precise memory tracking would consist of capturing allocation info of all new instances created during the method invocation and directly connected to that invocation - eg. created in the invoked method, in all methods invoked from the tracked one recursively and also in all runnables spawned anywhere in the tracked method call tree recursively. Getting this done might be a bit tricky but it is perfectly achievable by BTrace.