Search code examples
c#wmicpu-usage

Wrong calculated CPU usage using C# and WMI


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.


Solution

  • 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.