使用性能计数器的%Processor Time上的值不一致

时间:2012-12-21 12:50:26

标签: c# cpu-usage performancecounter

我有以下类来监视系统,以查看我的程序使用的总cpu以及系统的总cpu使用情况。问题是,有时,当我调用GetHealthInformation方法时,我的程序%CPU比系统的%CPU大。 这是我的代码:

    public class MonitoringManager : AbstractComponent, IMonitoringManager, IStaticComponent {
    private static PerformanceCounter totalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 
    private static PerformanceCounter cpuCounterMyProgram = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
    private static DateTime lastUpdate = DateTime.UtcNow;

    public void Load() {
        cpuCounterMyProgram.NextValue();
        totalCpuCounter.NextValue();
    }

    public  HealthInfo GetHealthInformation(){
        var now = DateTime.UtcNow;
        if((now - lastUpdate).TotalMilliseconds <1000){
            Thread.Sleep(1000);
        }
        lastUpdate = now;
        return new HealthInfo(totalCpuCounter.NextValue(), cpuCounterMyProgram.NextValue() / Environment.ProcessorCount);

    }

}


    public class HealthInfo{

    [DataMember]
    public float CpuTotal { get; set; }

    [DataMember]
    public float CpuMyProgram { get; set; }


    public HealthInfo(float cpuTotal, float cpuMyProgram){
        CpuTotal = cpuTotal;
        CpuMyProgram = cpuMyProgram;           
    }

    #endregion IConstructors
}

}

有什么问题?为什么有时系统的总CPU百分比是0%而我的程序是2%?

0 个答案:

没有答案