Search code examples
c#.netmemorymemory-managementclr

How to know the total memory allocated by a process since its creation


We are trying to setup a regression test environment on which our app would be installed, replayed some traffic and then compared with a "prod grade" version of the same app. After the replay, we would compare key metrics from both version, both business and technical.

One of the metrics is how much memory has been allocated by the process since its creation, to make sure the current version is not allocating significantly more than the "prod grade" version. But I cannot find in the PerformanceCounters or in the System.Diagnostics any metrics that would give us this information.

I understand that the GC frees memory all the time, but what I want to count is how much memory has been allocated a bit like System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime does for the CPU consumed (At least I think it does).

Edit: To say it differently, what I want to measure is the total memory in the gen0-1-2 PLUS all the memory that has been freed by the numerous GCs that have run in my process.

Thanks in advance.


Solution

  • For .Net Framework AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize gives this.

    For .Net Core there is also System.GC.GetTotalAllocatedBytes().

    I'm not sure what the difference is, in my experimenting System.GC.GetTotalAllocatedBytes(true) gave a very accurate count seeing even a single additional object allocation. System.GC.GetTotalAllocatedBytes(false) and AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize seem to give the same value and only update after several allocations.