Search code examples
c#openhardwaremonitor

Get VRAM Total using OpenHardwareMonitor NuGet package


I am currently trying to get the value of a GPU's total VRAM using the Nuget package OpenHardwareMonitor.

I know that it is possible to get the value through the use of the package, however, I have been trying for quite a while, and have not found the specific code for completing the task.

I am not looking for the answer of getting the total VRAM using any other means, such as WMI. I am just looking for an answer using OpenHardwareMonitor.

If you have the solution to this problem, that would be greatly appreciated!


Solution

  • The problem is that the NuGet package is built from an older version of the code. In the meantime additional sensors have been added that include details about total, free and used GPU memory (at least for NVidea GPU's). See this diff.

    If that package ever gets updated, you should be able to find the memory details in the list of sensors:

    var computer = new Computer();
    computer.GPUEnabled = true;
    computer.Open();
    var gpu = computer.Hardware.First(x => x.HardwareType == HardwareType.GpuNvidia);
    var totalVideoRamInMB = gpu.Sensors.First(x => x.Name.Equals("GPU Memory Total")).Value / 1024;
    computer.Close();
    

    Until then, a workaround would be to extract the memory information from the GetReport() result, where the GPU memory information looks like this:

    Memory Info
    
     Value[0]: 2097152
     Value[1]: 2029816
     Value[2]: 0
     Value[3]: 8221004
     Value[4]: 753168
    

    Where Value[0] is the total GPU memory and Value[4] the amount of free GPU memory in kB. So with some regex magic, we can extract that information:

    var pattern = @"Memory Info.*Value\[0\]:\s*(?<total>[0-9]+).*Value\[4\]:\s*(?<free>[0-9]+)";
    var computer = new Computer();
    computer.GPUEnabled = true;
    computer.Open();
    var gpu = computer.Hardware.First(x => x.HardwareType == HardwareType.GpuNvidia);
    var report = gpu.GetReport();
    var match = Regex.Match(report, pattern, RegexOptions.Singleline);
    var totalVideoRamInMB = float.Parse(match.Groups["total"].Value) / 1024;
    var freeVideoRamInMB = float.Parse(match.Groups["free"].Value) / 1024;
    computer.Close();
    

    Note that OpenHardwareMonitor only implements GPU memory information for NVidea GPU's.