I have a .NET 6.0 code I run repeatedly to monitor the CPU on a machine and send statistics to a dashboard server:
var stopwatch = Stopwatch.StartNew();
var processorQuery = new ManagementObjectSearcher().WMIquery("select * from Win32_Processor");
Log(stopwatch.ElapsedMilliseconds); // !!! 2 to 10 seconds!
// now process the results
var processors = new JArray();
foreach (var processorMO in processorQuery) {
var name = processorMO["Name"]?.ToString() ?? "";
var addressWidth = Double.Parse(processorMO["AddressWidth"]?.ToString() ?? "-1");
if (name.IndexOf(addressWidth.ToString()) != -1) name = $"{name} x{addressWidth}";
var maxClockSpeedGHz = Double.Parse(processorMO["MaxClockSpeed"]?.ToString() ?? "-1000") / 1000.0;
if (name.IndexOf(maxClockSpeedGHz.ToString()) != -1) name = $"{name} {maxClockSpeedGHz}GHz";
var numberOfCores = Double.Parse(processorMO["NumberOfCores"]?.ToString() ?? "-1");
name = $"{name} {numberOfCores}cores";
name = name.Replace("CPU ", " ").Replace(" M ", " M").Replace(" @ ", " ");
name = string.Join(" ", name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); // replace multiple spaces with single
int loadPercentage = (int)Double.Parse(processorMO["LoadPercentage"]?.ToString() ?? "-1");
processors.Add(new JObject() { { "Name", name }, { "LoadPercentage", loadPercentage } });
}
My issue is that the call to WMIquery
is extremely slow .. from 2.5 to 10 seconds!
Is there anything I am doing wrong ? is there a way to get this information faster ?
(PS which other tags are useful here?)
You can use GetSystemTimes which gives you for all cores the Idle, Kernel and User time. If you do this e.g. every second you can calculate overall CPU utilization by yourself in a much more efficient way.
See
and