java内存使用率,如何测量Java方法的内存使用率

sounds strange, but still.

Imagine I have a java method

boolean myMethod(Object param1, Object param2) {

// here can be some simple calculations. can be some services invokation

// or calls to DB. doesn't matter

return someValue;

}

How can I measure how much memory JVM uses to execute this method ? How much memory actually uses this method for its execution ?

Is there any tools or I maybe I can add some extra code to my method to be able to see used memory ?

I am using JConsole to monitor JVM, I also know that we can use java.lang.Runtime to see freeMemory, but actually I can't figure out how much memory my method uses with this tools.

解决方案

Measuring the true size of of each invocation of a method is not as simple as it sounds and the JVM does not support it. The complexity comes about a) because the JVM was designed to hide this low level detail and b) the JVM may have more than one variation of the same method in flight at any point of time, which sounds nuts but it is also true. Some times the method will have been inlined, or optimised more heavily or even recompiled in a special way to support hot swapping of the method while it is running (!) which can radically change its runtime size.

Measuring the amount of heap used by a method call

Given that method invocations do not use the heap, it is tempting to say 0 bytes. However one may want to know the size of any new object that was allocated by a method call. This can be answered, however objects are shared across method calls and threads. So one has to be very clear about what they want to measure, and take care to not count it twice. There are libraries that will give the size of an Object in Java, they usually work either by reflection and a heuristic or they wrap sun.misc.Unsafe to inspect pointers to the object and its data. For example http://code.google.com/p/javabi-sizeof/.

Measuring the allocation rate of a method

YourKit has an excellent tool described here for tracking every object allocation at its source point and reporting back their total size and rates. Very useful for finding out who is causing GC churn.

Measuring the amount of stack used per method call

The JVM does not publish this information, and as mentioned before it will vary depending on the optimizations that are currently active and which runtime compiler is being used.

The alternative is to use a heuristic. Something like counting up how many variables are used within the method and multiply the count by 4 to give an answer in bytes (which assumes that every variable is 4 bytes in size, ie an int). Obviously this heuristic is flawed and could be improved, but it is simple enough to give a quick and fairly representative answer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值