1

I would like to grab the GPU memory usage (dedicated and shared) from my C# code. Are there any chances to get these infos via WDDM or performance counter? How does the Taskmanager get these infos?

Since I also need the usage of AMD cards in particular, I can unfortunately not use NVAPI for this.

mFDev
  • 83
  • 7
  • 2
    System.Diagnostics.PerformanceCounter class, query for the "GPU Adapter Memory" counters. Verify by running perfmon.exe – Hans Passant Aug 11 '20 at 12:34

1 Answers1

3

There are 2 types of GPU memory - Dedicated Memory & Shared Memory. Dedicated memory remains smaller in size but GPU gives preference to this memory to do its operations. In C#, I have developed below code, which returns me the current usage of both these memories. You can cross verify the result in Task Manager.

var category = new PerformanceCounterCategory("GPU Adapter Memory");
var counterNames = category.GetInstanceNames();
var gpuCountersDedicated = new List<PerformanceCounter>();
var gpuCountersShared = new List<PerformanceCounter>();
var result = 0f;

foreach (string counterName in counterNames)
{
    foreach (var counter in category.GetCounters(counterName))
    {
        if (counter.CounterName == "Dedicated Usage")
        {
            gpuCountersDedicated.Add(counter);
        }
        else if (counter.CounterName == "Shared Usage")
        {
             gpuCountersShared.Add(counter);
        }
    }
}

gpuCountersDedicated.ForEach(x =>
{
    _ = x.NextValue();
});

await Task.Delay(1000);

gpuCountersDedicated.ForEach(x =>
{
    result += x.NextValue();
});

Console.WriteLine("Dedicated memory usage: " + result);

result = 0f;

gpuCountersShared.ForEach(x =>
{
    _ = x.NextValue();
});

await Task.Delay(1000);

gpuCountersShared.ForEach(x =>
{
    result += x.NextValue();
});

Console.WriteLine("Shared memory usage: " + result);

Output: Console Output

Task Manager: Snip from task manager

Tanjot
  • 31
  • 4