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.
Here is a C# code with performance counters:
public static void DumpProcessesCpu(string machineName)
{
List<PerformanceCounter> counters = new List<PerformanceCounter>();
foreach (Process process in Process.GetProcesses(machineName))
{
PerformanceCounter processorTimeCounter = new PerformanceCounter(
"Process",
"% Processor Time",
process.ProcessName,
machineName);
processorTimeCounter.NextValue();
counters.Add(processorTimeCounter);
}
Thread.Sleep(1000); // 1 second wait, needed to get a sample
foreach (PerformanceCounter processorTimeCounter in counters)
{
Console.WriteLine("Process:{0} CPU% {1}",
processorTimeCounter.InstanceName,
processorTimeCounter.NextValue());
}
}
It's inspired from here: https://learn.microsoft.com/en-us/archive/blogs/bclteam/how-to-read-performance-counters-ryan-byington You can't really be faster than this, the reason why is explained in the article. Basically, you'll have to read the value twice to get it right, so you need to wait between samples.
However, depending on what you want to do, for example, suppose you want to write a "remote task manager", you can code all this in a background task (thread) and regularly update the values so the end-user will not really see the delay between samples.
Here is a C# block of code tested and validated and thanks to fejesjoco, I used his code and made the test to get it to work.
public class CPUUtilizationTests
{
[Test]
public void TestPercentProcessorTime()
{
Assert.That(PercentProcessorTime("Idle"), Is.Not.GreaterThan(100.0));
}
public float PercentProcessorTime(string processName)
{
var mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
var run1 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);
System.Threading.Thread.Sleep(1000); // can be an arbitrary number
var run2 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);
if (!run2.ContainsKey(processName)) throw new Exception(string.Format("Process not found: {0}", processName));
string percentageProcessorTime = "PercentProcessorTime";
string total = "_Total";
ulong percentageDiff = (ulong)run2[processName][percentageProcessorTime] - (ulong)run1[processName][percentageProcessorTime];
ulong totalDiff = (ulong)run2[total][percentageProcessorTime] - (ulong)run1[total][percentageProcessorTime];
return ((float)percentageDiff / (float)totalDiff)*100.0f;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With