• C# 准确获取系统 CPU 使用率


    1.  PerformanceCounter 注意:(32位下不是线程安全的)

    public class ProcessorUsage
    {
        const float sampleFrequencyMillis = 1000;
    
        protected object syncLock = new object();
        protected PerformanceCounter counter;
        protected float lastSample;
        protected DateTime lastSampleTime;
    
        /// <summary>
        /// 
        /// </summary>
        public ProcessorUsage()
        {
            this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
        }
    
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public float GetCurrentValue()
        {
            if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
            {
                lock (syncLock)
                {
                    if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
                    {
                        lastSample = counter.NextValue();
                        lastSampleTime = DateTime.UtcNow;
                    }
                }
            }
    
            return lastSample;
        }
    }
    

    2.WMI

    ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");
                var cpuTimes = searcher.Get()
                    .Cast<managementobject>()
                    .Select(mo => new
                    {
                        Name = mo["Name"],
                        Usage = mo["PercentProcessorTime"]
                    }
                    )
                    .ToList();
    
    var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage);
    var cpuUsage = query.SingleOrDefault();
    

      

  • 相关阅读:
    制作dos启动u盘
    服务器之ECC报错检查
    shc 对 Linux shell 脚本加密.
    Linux
    windows查看端口占用
    python语言
    AppScan9.0安装破解
    局域网灰色设置解除
    shell脚本
    nginx安装
  • 原文地址:https://www.cnblogs.com/mschen/p/8031110.html
Copyright © 2020-2023  润新知