开发者

How to test memory used considering garbage collector?

I am testing a sorting algorithm, and I would like to test the average used memory by testing 1000 random vectors. The problem is when I run about the 20 random vector inside a loop, the garbage collector run and I lose the calculation. What should I do please? I don't want to test it manual one by one =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));


OK, so I'm a little late here and you have probably solved this by now, but just in case someone else wants to know, The easiest way to prevent the GC from cleaning up an object is to keep a reference to it in another object. For every object you create add it to some sort of container like an array/hash/vector/list or whatever your language supports. Eg:

var items as Array[0..numberOfItems]

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

The container would add some overhead so you would need to measure it first then subtract that amount from the final output. For example:

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

You would then do the same measurements as you did, inserting each vector into an array and subtract arrayOverhead from the memory usage to get your final result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜