1

So I'm writing a task manager clone, and right now I'm using this to calculate the CPU usage %s of each process. The problem is this is very slow; I was just wondering if there is a way to speed this up.

Also, I'm not allowed to use PerformanceCounter's methods and/or 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;
        }
    }
}
Bertie Wheen
  • 1,215
  • 1
  • 13
  • 20

1 Answers1

2

Use PerformanceCounter components to get different performance statistics:

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

And here is sample of creating something like task manager.

Also consider using Win API function GetProcessTimes.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459