I want to get some idea how much memory has been cumulatively allocated by a thread. From it's documentation GC.GetAllocatedBytesForCurrentThread()
seems like the thing to use, but in practice, it's giving me... something else.
Here's my test program, created using the dotnet core 3.1 console application Visual Studio template.
using System;
class Program {
static void Main() {
long start, difference;
start = GC.GetAllocatedBytesForCurrentThread();
var x = new int[1_000_000];
difference = GC.GetAllocatedBytesForCurrentThread() - start;
Console.WriteLine("{0} bytes allocated for array construction", difference);
start = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine(DateTime.Now.ToString());
difference = GC.GetAllocatedBytesForCurrentThread() - start;
Console.WriteLine("{0} bytes allocated for date printing", difference);
}
}
It gives me this output.
0 bytes allocated for array construction
9/17/2020 11:26:40 AM
19040 bytes allocated for date printing
Press any key to continue . . .
I don't believe that a one-million element array can be created without allocating a single byte on the heap.
So is there a way to track heap allocations for a thread? And what is this method actually doing, if anything?
Here's a longer, more comprehensive test program including all the suggestions so far. I included the sum part to verify that array actually gets created when the code runs.
using System;
using System.Linq;
class Program {
static void Main() {
long start, difference;
{
start = GC.GetAllocatedBytesForCurrentThread();
var x = new int[1_000_000];
x[^1] = 7;
difference = GC.GetAllocatedBytesForCurrentThread() - start;
Console.WriteLine("{0} bytes thread allocated for array construction (sum: {1})", difference, x.Sum());
}
start = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine(DateTime.Now.ToString());
difference = GC.GetAllocatedBytesForCurrentThread() - start;
Console.WriteLine("{0} bytes thread allocated for date printing", difference);
{
start = GC.GetTotalMemory(true);
var x = new int[1_000_000];
x[^1] = 7;
difference = GC.GetTotalMemory(true) - start;
Console.WriteLine("{0} bytes total allocated for array construction (sum: {1})", difference, x.Sum());
}
start = GC.GetTotalMemory(true);
Console.WriteLine(DateTime.Now.ToString());
difference = GC.GetTotalMemory(true) - start;
Console.WriteLine("{0} bytes total allocated for date printing", difference);
}
}
Output:
0 bytes thread allocated for array construction (sum: 7)
9/17/2020 11:51:54 AM
19296 bytes thread allocated for date printing
4000024 bytes total allocated for array construction (sum: 7)
9/17/2020 11:51:54 AM
64 bytes total allocated for date printing