[英]CPU usage does not match Task Manager, PerformanceCounter or ManagementObjectSearcher
我只是想獲得與任務管理器匹配的准確 CPU 使用率。 到目前為止,我已經嘗試了四種不起作用的推薦方法。
首先,鑒於我能找到,我嘗試了類似的解決方案或建議。 這里的代碼示例使用了四種方法,都是不准確的。 其次,我知道任務管理器會波動並取決於采樣時間。 這仍然不能解釋差異。 最后,我知道有不同的方法,而任務管理器只使用一種方法。 由於這是面向一般用戶的,因此需要靠近任務管理器。
public partial class MainWindow : Window
{
//*** Method 1 & 2
PerformanceCounter cpuCounterPi = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
PerformanceCounter cpuCounterP = new PerformanceCounter("Processor", "% Processor Time", "_Total");
//*** method 3
ManagementObjectSearcher query1 = new ManagementObjectSearcher("select loadpercentage from win32_processor");
//*** Mixed method usage below
CounterSample csPi1, csPi2, csP1, csP2;
double cpuPercentagePi, cpuPercentageP, cpuPercentageLoad;
int count = -1;
Boolean alternate = false;
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 5);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
count++;
//***Method 1 & 2
if (alternate)
{
csPi1 = cpuCounterPi.NextSample();
cpuPercentagePi = CounterSample.Calculate(csPi2, csPi1);
csP1 = cpuCounterP.NextSample();
cpuPercentageP = CounterSample.Calculate(csP2, csP1);
}
else
{
csPi2 = cpuCounterPi.NextSample();
cpuPercentagePi = CounterSample.Calculate(csPi1, csPi2);
csP2 = cpuCounterP.NextSample();
cpuPercentageP = CounterSample.Calculate(csP1, csP2);
}
alternate = !alternate;
if (count==5) { textBox.Clear(); count = 0; }
textBox.Text = textBox.Text + "\nProcessor Information (Method 1) " + cpuPercentagePi.ToString();
textBox.Text = textBox.Text + "\nProcessor (Method 2) " + cpuPercentageP.ToString();
textBox.Text = textBox.Text + "\nProcessor ½ (Method 2 divided by 2) " + (cpuPercentageP/2).ToString();
//***** Method 3 ****
ManagementObjectCollection cpuColl = query1.Get();
foreach (ManagementObject mo in cpuColl)
{
cpuPercentageLoad = Convert.ToDouble(mo["loadpercentage"]);
}
textBox.Text = textBox.Text + "\nProcessor Load (Method 3) " + cpuPercentageLoad.ToString() + "\n";
}
從圖中可以看出我有一個雙核 CPU,有四個邏輯處理器。 CPU 是 Intel Skylake i7-6650U,運行 Windows 10。
謝謝
供參考 - 這些鏈接是類似的: PerformanceCounter 報告的 CPU 使用率比觀察到的要高How to get the CPU Usage in C#? 計算 Windows 進程的 CPU 使用率?
您有 2 個內核但有 4 個線程,因此您需要除以 4,而不是 2。此外,我懷疑您的 WMI 方法只會檢查 1 個內核。 檢查實際上是否有多個win32_processor
對象可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.