ManagementObjectSearcher WMIquery very slow

Viewed 180

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?)

2 Answers

It's slow because you're doing select * which includes such things as LoadPercentage which isn't something that WMI acquires from its database, it's real-time info that's tested at the point of querying and takes at least a second to complete and give an accurate assessment of the load. Since it seems you actually need LoadPercentage there's nothing much you can do other than just wait. I would not worry about this at all, maybe focus more on the CPU/IO penalty inhibited by each query.

Related