更有效的计算CPU使用率的方法

时间:2012-10-19 22:36:34

标签: c# .net performance

所以我正在编写一个任务管理器克隆,现在我正在使用它来计算每个进程的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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

使用PerformanceCounter组件获取不同的效果统计信息:

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

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

另请考虑使用Win API函数GetProcessTimes