How to get CPU usage for more than 2 cores?

前端 未结 5 450
甜味超标
甜味超标 2020-12-03 15:57

I try to get in my program CPU usage divided by a cores. Now I use the PerformanceCounter and changing the InstanceName between 0 and 1 I have the data from 2 cores.

5条回答
  •  甜味超标
    2020-12-03 16:30

    Some thing like this should also work for your requirement

    public List GetServerStatus()
    {
        List cpuStatus = new List();
        ObjectQuery wmicpus = new WqlObjectQuery("SELECT * FROM Win32_Processor");
        ManagementObjectSearcher cpus = new ManagementObjectSearcher(wmicpus);
        try
        {
            int coreCount = 0;
            int totusage = 0;               
            foreach (ManagementObject cpu in cpus.Get())
            {
                //cpuStatus.Add(cpu["DeviceId"] + " = " + cpu["LoadPercentage"]);
                coreCount += 1;
                totusage += Convert.ToInt32(cpu["LoadPercentage"]);
            }
            if (coreCount > 1)
            {
                double ActUtiFloat = totusage / coreCount;
                int ActUti = Convert.ToInt32(Math.Round(ActUtiFloat));
                //Utilisation = ActUti + "%";
                cpuStatus.Add("CPU = " + ActUti);
            }
            else
            {
                cpuStatus.Add("CPU = " + totusage);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cpus.Dispose();
        }            
        return cpuStatus;
    }
    

提交回复
热议问题