I wrote a piece of code that measures the memory consumption for a method(average memory and peak memory values). I simply run the method in a thread and call the GC.GetTotalMemory(false) in a loop that checks if the thread is still alive and then calculates current memory and adds it to "totalmem" variable to get the average later. Also I call this analyzer in a loop because I need to run it on multiple set of different parameters (measuring consumption in different files for example) so I need to wait till the single thread finishes and collect garbage then start the next analysis. My question is: Is this a bad way and will the output be close to the real one or accurate? Is measuring a single thread memory equals to measuring process memory?
double totalmem = 0;
long iterationsCount = 0;
double PeakMemory = 0;
var t = new Thread(() =>
{
int output = methodToAnalyze(int a, string b);
}
Console.WriteLine("Finished thread");
});
t.Start();
Console.WriteLine("Started thread running");
while (t.IsAlive)
{
var mem = (double)GC.GetTotalMemory(false);
// convert to MB
mem = mem / (1024 * 1024);
totalmem += mem;
iterationsCount ++;
if (mem > PeakMemory)
{
PeakMemory = mem;
}
}
t.Join();
var AverageMemory = (totalmem / iterationsCount);
var ElapsedTimeInMs = elapsedMs;