zoukankan      html  css  js  c++  java
  • 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();
    

      

  • 相关阅读:
    WebContent的子目录里面的jsp文件无法将数据传递给Servlet
    MVC 与 三层架构
    使用命令行操作MySQL 及 语法
    JDBC
    字符典
    servlet 生命周期
    6 shell内置命令
    5shell中的数组
    4shell中的特殊变量
    3shell命令替换
  • 原文地址:https://www.cnblogs.com/mschen/p/8031110.html
Copyright © 2011-2022 走看看