Java单元测试:如何测量方法调用的内存占用量 [英] Java unit testing: how to measure memory footprint for method call
问题描述
假设我有一个类进行一些繁重的处理,使用多个集合进行操作。我想要做的是确保这样的操作不会导致内存不足甚至更好我想设置一个可以使用多少内存的阈值。
Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.
class MyClass()
{
public void myMethod()
{
for(int i=0; i<10000000; i++)
{
// Allocate some memory, may be several collections
}
}
}
class MyClassTest
{
@Test
public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()
{
new MyClass().myMethod();
// How do I measure amount of memory it may try to allocate?
}
}
这样做的正确方法是什么?或者这不可能/不可行?
What is the right approach to do this? Or this is not possible/not feasible?
推荐答案
我可以想到几个选项:
- 通过微基准测试找出你的方法需要多少内存(即 JMH )。
- 基于启发式估算构建分配策略。有几种实现类大小估计的开源解决方案,即 ClassSize 。一种更简单的方法可以是利用缓存来释放很少使用的对象(即番石榴的缓存)。正如@EnnoShioji所提到的,Guava的缓存具有基于内存的驱逐策略。
- Finding out how much memory your method requires via a microbenchmark (i.e. jmh).
- Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. ClassSize. A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies.
您还可以编写自己的基准测试来计算内存。想法是
You can also write your own benchmark test which counts memory. The idea is to
- 让一个线程运行。
- 创建一个新数组来存储你的要分配的对象。因此,在GC运行期间不会收集这些对象。
-
System.gc()
,memoryBefore = runtime.totalMemory() - runtime.freeMemory()
- 分配对象。将它们放入数组中。
-
System.gc()
,memoryAfter = runtime.totalMemory() - runtime.freeMemory()
- Have a single thread running.
- Create a new array to store your objects to allocate. So these objects won't be collected during GC run.
System.gc()
,memoryBefore = runtime.totalMemory() - runtime.freeMemory()
- Allocate your objects. Put them into the array.
System.gc()
,memoryAfter = runtime.totalMemory() - runtime.freeMemory()
这是我在轻量级微基准工具能够以字节精度测量内存分配。
This is a technique I used in my lightweight micro-benchmark tool which is capable of measuring memory allocation with byte-precision.
这篇关于Java单元测试:如何测量方法调用的内存占用量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!