Returning CPU usage in WMI using C#

jpavlov picture jpavlov · Mar 19, 2012 · Viewed 29k times · Source

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.

Answer

L.B picture L.B · Mar 19, 2012
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();