获取cpu和内存使用情况

Posted microstep

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取cpu和内存使用情况相关的知识,希望对你有一定的参考价值。

public class SystemInfo
    {
        [DllImport("kernel32")]
        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
        [DllImport("kernel32")]
        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
        [DllImport("kernel32")]
        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
        [DllImport("kernel32")]
        public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);

        PerformanceCounter cpu; MEMORY_INFO MemInfo;

        public SystemInfo()
        {
            cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");

            MemInfo = new MEMORY_INFO();
        }

        public float[] GetSystemInfo()
        {
            float[] ret = new float[2];
            
            GlobalMemoryStatus(ref MemInfo);
            ret[1] = MemInfo.dwMemoryLoad;
            ret[0] = cpu.NextValue();

            return ret;
        }
    }

    //定义CPU的信息结构  
    [StructLayout(LayoutKind.Sequential)]
    public struct CPU_INFO
    {
        public uint dwOemId;
        public uint dwPageSize;
        public uint lpMinimumApplicationAddress;
        public uint lpMaximumApplicationAddress;
        public uint dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public uint dwProcessorLevel;
        public uint dwProcessorRevision;
    }
    //定义内存的信息结构  
    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_INFO
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public uint dwTotalPhys;
        public uint dwAvailPhys;
        public uint dwTotalPageFile;
        public uint dwAvailPageFile;
        public uint dwTotalVirtual;
        public uint dwAvailVirtual;
    }
    //定义系统时间的信息结构  
    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEMTIME_INFO
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    }

 

以上是关于获取cpu和内存使用情况的主要内容,如果未能解决你的问题,请参考以下文章

获取cpu和内存使用情况

C#获取特定进程CPU和内存使用率

获取进程的CPU和内存使用情况的正确性能计数器是什么?

Python 系统资源信息获取CPU 和内存使用情况

获取rds的cpu和内存使用情况

请教下:C语言获取计算机系统CPU使用率,内存使用情况的思路或流程是怎样的?!