Count number of gc's that occur during a unit

2019-03-03 07:58发布

I am currently writing a unit test to see the performance impact of a given method. From practice we observed that currently lots of gc's are occurring during the execution of the given method. I was wondering whether it is possible to see how many gcs occurred during the method run from java.

2条回答
该账号已被封号
2楼-- · 2019-03-03 08:32

You can use GarbageCollectorMXBean to get the count of garbage collections.

You can do something like this:

Collection<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
    String gcName = garbageCollectorMBean.getName();
    long gcCount = garbageCollectorMBean.getCollectionCount();
}
查看更多
乱世女痞
3楼-- · 2019-03-03 08:36

Can't you simply call this method with the parameters and count them?

 java -verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails TestFunc

Point 1

If you have GC calls during your method you will get wrong results. All GC calls are Stop The World calls for some phases of the algorithm, this meaning that your Threads are put on hold for that particular time. For how much it depends on the application that you are running, the heap you are giving to the JVM and the GC algorithm that you choose for the young and old generation. Note that calls to young generation are way cheaper then those in the old generation.

Point 2

Benchmarking in Java is complicated, mainly because of the JIT. You should use a library for your tests (if you can). One very good is JMH. If you can't use one, then let the jvm heat up a bit before running the actual benchmark, like 10000 times running the same method then measuring is usually the recommended.

查看更多
登录 后发表回答