Pad*_*256 5 c# performancecounter cpu-usage
我只是想获得与任务管理器匹配的准确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";
}
Run Code Online (Sandbox Code Playgroud)
从图中可以看出,我有一个双核CPU,有四个逻辑处理器.CPU是Intel Skylake i7-6650U,运行Windows 10.
谢谢
供参考 - 这些链接类似: PerformanceCounter报告的CPU使用率高于观察到的 如何获得C#中的CPU使用率? 计算Windows进程的CPU使用率?
| 归档时间: |
|
| 查看次数: |
1050 次 |
| 最近记录: |