This is my function for enumerating processes on windows box and calculating percentage of CPU usage for each process but results are not correct.
CPU usage does't add up to 100% but more like to 120% or 130% and I don't know what I'm doing wrong. It seems like it calculats right CPU usage for varoius apps like firefox, VS2010, office,.. but has problems with System Idle Process.
public List<ProcInfo> GetRunningProcesses()
{
List<ProcInfo> allProcesses = new List<ProcInfo>();
UInt64 currentProcessCpuTime = 0;
UInt64 allProcessCpuTime = 0;
SelectQuery wmiQuery = new SelectQuery("SELECT Name, Description, ProcessId, KernelModeTime, UserModeTime FROM Win32_Process");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(connectionScope, wmiQuery);
ManagementObjectCollection moc = oSearcher.Get();
foreach (ManagementObject mo in moc)
{
allProcessCpuTime += (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
}
foreach (ManagementObject mo in moc)
{
currentProcessCpuTime = (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
allProcesses.Add(new ProcInfo((string)mo["Name"], (string)mo["Description"], (UInt32)mo["ProcessId"], (currentProcessCpuTime / (double)allProcessCpuTime * 100));
}
return allProcesses;
}
EDIT:
I found that my function is all wrong.
I'm starting a bounty for the best working solution. Solution needs to work for local and remote system and should be fast.