Search code examples
c#wmi

Returning CPU usage in WMI using C#


To return the CPU usage by using WMI, do I return the PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor?

If not, which class should I look towards? Thanks.


Solution

  • ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
    foreach (ManagementObject obj in searcher.Get())
    {
        var usage = obj["PercentProcessorTime"];
        var name = obj["Name"];
        Console.WriteLine(name +" : " + usage);
    }
    

    And for Linq lovers

    ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
    var cpuTimes = searcher.Get()
        .Cast<ManagementObject>()
        .Select(mo => new
            {
                Name = mo["Name"],
                Usage = mo["PercentProcessorTime"]
            }
        )
        .ToArray();