【问题标题】:More efficient way to calculate CPU Usage计算 CPU 使用率的更有效方法
【发布时间】:2012-10-19 22:36:33
【问题描述】:

所以我正在编写一个任务管理器克隆,现在我正在使用它来计算每个进程的 CPU 使用率 %s。问题是这非常慢;我只是想知道是否有办法加快速度。

另外,我不允许使用 PerformanceCounter 的方法和/或 WMI。

//Omitted:
// - Process[] processes just holds the currently running processes
// - rows[] is a list of the rows I have in a table which shows the tables data
// - rows[2] is the column for CPU usage
// - rows[0] is the column for PID
//========
//Do CPU usages
double totalCPUTime = 0;
foreach (Process p in processes)
{
    try
    {
        totalCPUTime += p.TotalProcessorTime.TotalMilliseconds;
    }
    catch (System.ComponentModel.Win32Exception e)
    {
        //Some processes do not give access rights to view their time.
    }
}
foreach (Process p in processes)
{
    double millis = 0;
    try
    {
        millis = p.TotalProcessorTime.TotalMilliseconds;
    }
    catch (System.ComponentModel.Win32Exception e)
    {
        //Some processes do not give access rights to view their time.
    }
    double pct = 100 * millis / totalCPUTime;
    for (int i = 0; i < rows.Count; i++)
    {
        if(rows[i].Cells[0].Value.Equals(p.Id))
        {
            rows[i].Cells[2].Value = pct;
            break;
        }
    }
}

【问题讨论】:

标签: c# .net performance


【解决方案1】:

使用PerformanceCounter组件获取不同的性能统计:

var cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
double value = cpuCounter.NextValue();    

here 是创建任务管理器之类的示例。

还可以考虑使用 Win API 函数GetProcessTimes

【讨论】:

  • 我不允许使用 PerformanceCounter 的方法和/或 WMI。我会将其编辑到 OP 中
  • @BertieWheen 是否有您允许使用的列表? :)
  • 是的。然而,与此相关的事情主要是无法使用 PerformanceCounter 或 WMI。哦,显然我可以使用的最大 .NET 版本是 2.0,但这可能不适用。
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2012-11-12
  • 2012-06-13
  • 1970-01-01
  • 2020-12-02
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多