如何测试使用垃圾收集器的内存?

时间:2011-04-30 02:56:23

标签: java memory memory-management garbage-collection

我正在测试排序算法,我想通过测试1000个随机向量来测试平均使用的内存。问题是当我在循环中运行20个随机向量时,垃圾收集器运行并且我丢失了计算。我该怎么办?我不想逐一测试它= X。

for(int j = 0; j < 1000; j++)
{
    int vetOriginal[] = Generate(); 
    for(int i = 0; i < 10; i++)
    {
        int vetParaTeste[] = vetOriginal.clone();
        long memoriaInicial = Runtime.getRuntime().freeMemory() / 1024;
        mergeSort(vetParaTeste);
        somaMemoriaKB += memoriaInicial - Runtime.getRuntime().freeMemory()/1024;
    }
}
System.out.println("Average memory used: " + somaMemoriaKB / (1000* 10));

1 个答案:

答案 0 :(得分:2)

好的,所以我在这里有点晚了你现在可能已经解决了这个问题,但是万一其他人想知道,阻止GC清理对象的最简单方法是保持对它在另一个对象中。对于您创建的每个对象,将其添加到某种容器,如数组/散列/向量/列表或您支持的语言。例如:

var items as Array[0..numberOfItems]

for (var i = 0; i < numberOfItems; i++) {
    var vector = createVector()
    items[i] = vector;
}

容器会增加一些开销,因此您需要先测量它,然后从最终输出中减去该数量。例如:

var baseMemory = measureMemory()
var numberOfItems = 1000

// create an array of a known size (eg 1000 bytes)
var arrayOfKnownSize as Array[0..numberOfItems]

for (var i = 0; i < numberOfItems; i++)
    arrayOfKnownSize[i] = Int32(0xFF)

// calculate the size occupied by just the data ...
var expectedMemory = sizeOf(Int32) * numberOfItems 

// ... subtract this from the total memory usage and you will get the overhead 
var arrayOverhead = measureMemory() - baseMemory - expectedMemory

// now measure the memory used by an array of vectors
baseMemory = measureMemory()
var vectors as Array[0..numberOfItems]

for (var i = 0; i < numberOfItems; i++) {
    var vector = createVector()
    vectors[i] = vector;
}

// subtract the array overhead from the memory usage
var usedMemory = measureMemory() - baseMemory - arrayOverhead
var averageMemory = usedMemory / numberOfItems

然后,您将执行与您相同的测量,将每个矢量插入到数组中,并从内存使用中减去arrayOverhead以获得最终结果。