欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何用C#实时获取CPU利用率

程序员文章站 2023-11-03 13:20:10
获取内存使用率 方式1: using System; using System.Runtime.InteropServices; namespace ConsoleApp1 { public class Class1 { static void Main(string[] args) { Conso ......

 

获取内存使用率

方式1:

using system;
using system.runtime.interopservices;

namespace consoleapp1
{
    public class class1
    {
        static void main(string[] args)
        {
            console.writeline("总内存:" + formatsize(gettotalphys()));
            console.writeline("已使用:" + formatsize(getusedphys()));
            console.writeline("可使用:" + formatsize(getavailphys()));
            console.readkey();
        }

        #region 获得内存信息api
        [dllimport("kernel32.dll")]
        [return: marshalas(unmanagedtype.bool)]
        public static extern bool globalmemorystatusex(ref memory_info mi);

        //定义内存的信息结构
        [structlayout(layoutkind.sequential)]
        public struct memory_info
        {
            public uint dwlength; //当前结构体大小
            public uint dwmemoryload; //当前内存使用率
            public ulong ulltotalphys; //总计物理内存大小
            public ulong ullavailphys; //可用物理内存大小
            public ulong ulltotalpagefile; //总计交换文件大小
            public ulong ullavailpagefile; //总计交换文件大小
            public ulong ulltotalvirtual; //总计虚拟内存大小
            public ulong ullavailvirtual; //可用虚拟内存大小
            public ulong ullavailextendedvirtual; //保留 这个值始终为0
        }
        #endregion

        #region 格式化容量大小
        /// <summary>
        /// 格式化容量大小
        /// </summary>
        /// <param name="size">容量(b)</param>
        /// <returns>已格式化的容量</returns>
        private static string formatsize(double size)
        {
            double d = (double)size;
            int i = 0;
            while ((d > 1024) && (i < 5))
            {
                d /= 1024;
                i++;
            }
            string[] unit = { "b", "kb", "mb", "gb", "tb" };
            return (string.format("{0} {1}", math.round(d, 2), unit[i]));
        }
        #endregion

        #region 获得当前内存使用情况
        /// <summary>
        /// 获得当前内存使用情况
        /// </summary>
        /// <returns></returns>
        public static memory_info getmemorystatus()
        {
            memory_info mi = new memory_info();
            mi.dwlength = (uint)system.runtime.interopservices.marshal.sizeof(mi);
            globalmemorystatusex(ref mi);
            return mi;
        }
        #endregion

        #region 获得当前可用物理内存大小
        /// <summary>
        /// 获得当前可用物理内存大小
        /// </summary>
        /// <returns>当前可用物理内存(b)</returns>
        public static ulong getavailphys()
        {
            memory_info mi = getmemorystatus();
            return mi.ullavailphys;
        }
        #endregion

        #region 获得当前已使用的内存大小
        /// <summary>
        /// 获得当前已使用的内存大小
        /// </summary>
        /// <returns>已使用的内存大小(b)</returns>
        public static ulong getusedphys()
        {
            memory_info mi = getmemorystatus();
            return (mi.ulltotalphys - mi.ullavailphys);
        }
        #endregion

        #region 获得当前总计物理内存大小
        /// <summary>
        /// 获得当前总计物理内存大小
        /// </summary>
        /// <returns&amp;gt;总计物理内存大小(b)&amp;lt;/returns&amp;gt;
        public static ulong gettotalphys()
        {
            memory_info mi = getmemorystatus();
            return mi.ulltotalphys;
        }
        #endregion
    }
}

 方式2:

备注:需要添加 system.management 的引用

using system;
using system.management;

namespace consoleapp1
{
    public class class1
    {
        static void main(string[] args)
        {
            //需要添加 system.management 的引用


            //获取总物理内存大小
            managementclass cimobject1 = new managementclass("win32_physicalmemory");
            managementobjectcollection moc1 = cimobject1.getinstances();
            double available=0, capacity=0;
            foreach (managementobject mo1 in moc1)
            {
                capacity += ((math.round(int64.parse(mo1.properties["capacity"].value.tostring()) / 1024 / 1024 / 1024.0, 1)));
            }
            moc1.dispose();
            cimobject1.dispose();


            //获取内存可用大小
            managementclass cimobject2 = new managementclass("win32_perfformatteddata_perfos_memory");
            managementobjectcollection moc2 = cimobject2.getinstances();
            foreach (managementobject mo2 in moc2)
            {
                available += ((math.round(int64.parse(mo2.properties["availablembytes"].value.tostring()) / 1024.0, 1)));

            }
            moc2.dispose();
            cimobject2.dispose();

            console.writeline("总内存=" + capacity.tostring() + "g");
            console.writeline("可使用=" + available.tostring() + "g");
            console.writeline("已使用=" + ((capacity - available)).tostring() + "g," + (math.round((capacity - available) / capacity * 100, 0)).tostring() + "%");
            console.readkey();
        }
    }
}

 

 

获取cpu使用率

using system;
using system.diagnostics;

namespace consoleapp1
{
    public class class1
    {
        static void main(string[] args)
        {
            performancecounter cpucounter;
            performancecounter ramcounter;

            cpucounter = new performancecounter();
            cpucounter.categoryname = "processor";
            cpucounter.countername = "% processor time";
            cpucounter.instancename = "_total";
            cpucounter = new performancecounter("processor", "% processor time", "_total");
            ramcounter = new performancecounter("memory", "available mbytes");



            console.writeline("电脑cpu使用率:" + cpucounter.nextvalue() + "%");
            console.writeline("电脑可使用内存:" + ramcounter.nextvalue() + "mb");
            console.writeline();



            while (true)
            {
                system.threading.thread.sleep(1000);
                console.writeline("电脑cpu使用率:" + cpucounter.nextvalue() + " %");
                console.writeline("电脑可使用内存:" + ramcounter.nextvalue() + "mb");
                console.writeline();

                if ((int)cpucounter.nextvalue() > 80)
                {
                    system.threading.thread.sleep(1000 * 60);
                }
            }
        }
    }
}

 

 

相关链接 :