C# 获取计算机CPU使用率/内存使用率/磁盘使用率

 

CPU:

void Main()
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("select PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");
    var cpuItem = searcher.Get().Cast().Select(item => new { PercentProcessorTime = item["PercentProcessorTime"] }).First();
    if (cpuItem != null && cpuItem.PercentProcessorTime != null)
        Debug.Print("CPU:" + cpuItem.PercentProcessorTime.ToString());
}

 

Disk:

public static Dictionary<string,int> GetDisksUsedRate()
{
    var result = new Dictionary<string,int>();
    var searcher = new ManagementObjectSearcher("Select Name,PercentDiskTime from Win32_PerfFormattedData_PerfDisk_PhysicalDisk WHERE Name != \"_Total\"");
    var diskItems = searcher.Get().Cast().ToList();
    foreach (var diskItem in diskItems)
        result.Add(diskItem["Name"].ToString(), Convert.ToInt32(diskItem["PercentDiskTime"]));
    return result;
}

 

Memory:

#region 获取内存使用率

        #region 可用内存

        /// 
        ///     获取可用内存
        /// 
        internal static long? GetMemoryAvailable()
        {
            const int MbDiv = 1024 * 1024;
            long availablebytes = 0;
            var managementClassOs = new ManagementClass("Win32_OperatingSystem");
            foreach (var managementBaseObject in managementClassOs.GetInstances())
                if (managementBaseObject["FreePhysicalMemory"] != null)
                    availablebytes = 1024 * long.Parse(managementBaseObject["FreePhysicalMemory"].ToString());
            return availablebytes / MbDiv;
        }

        #endregion

        internal static double? GetMemoryUsed()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
            double currentMemoryUsed = (double)MemoryUsed ;
            return currentMemoryUsed ;
        }

        private static long? GetPhysicalMemory()
        {
            //获得物理内存
            const int MbDiv = 1024 * 1024;
            var managementClass = new ManagementClass("Win32_ComputerSystem");
            var managementObjectCollection = managementClass.GetInstances();
            foreach (var managementBaseObject in managementObjectCollection)
                if (managementBaseObject["TotalPhysicalMemory"] != null)
                    return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString()) / MbDiv;
            return null;
        }

        public static double? GetMemoryUsedRate()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsedRate =(double?)(PhysicalMemory - MemoryAvailable)/ PhysicalMemory;
            return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * 100) : 0;
        }

        #endregion

 

你可能感兴趣的:(C# 获取计算机CPU使用率/内存使用率/磁盘使用率)