Reputation: 321
I know on the question of how to get the CPU load (per core and total), there are dozens of tutorials or code snippets.
But what makes me suspicious:
On the picture you can see my output on the left side and the Task Manager on the right side. So I expect a value of 13% for _Total (according to Task Manager) and not 1%. And why 1% is displayed even though one core has 6% and the other 12% is not really clear to me.
Here my code:
public SystemStatsViewModel() {
TimerThread = new Thread(new ThreadStart(TimerThreadMethod))
{
Name = "TimerThread",
IsBackground = true
};
TimerThread.Start();
}
private void TimerThreadMethod()
{
var cpuSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE Name LIKE '0%'");
string cpuString;
while (true)
{
cpuString = "";
foreach (var obj in cpuSearcher.Get())
{
cpuString += $"{obj["Name"]}: {obj["PercentProcessorTime"]}{Environment.NewLine}";
}
}
}
UPDATE
With the perf counters I have already tried it, so WMI and perf counters (various counters) did not provide the desired value. But there is the performance monitor under Windows itself (Win + R, perfmon, Enter). Here you can find the indicator "processor load" under "processor information". And I do NOT mean the "Processor time (%)". The value at least comes closest to the value displayed by the Task Manager. But I couldn't figure out how to retrieve it yet. (I use a German Windows, have already tried to set it to English, but the counters stay with the German names, otherwise I would have seen what the counter is called in English (at least in Windows)).
But with "processor load" or "processor usage" nothing was found. And also displaying the counters of the category processor information does not show that specific counter. So it must be something that is calculated from several counters itself.
Upvotes: 1
Views: 1021
Reputation: 11
public int GetCPUUsage()
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
return (int)cpuCounter.NextValue();
}
I've been using this... It seems to match the Task Manager Total CPU value.
Upvotes: 0