C# 获取CPU使用率 附源码

下面是源码:

using System;
using System.Diagnostics;
using System.IO;




namespace cpu_get_info
{
    class Program
    {
        static void write_logs(string str)
        {
            //获取和设置当前目录。
            string strFilePath = System.Environment.CurrentDirectory;
            strFilePath = strFilePath + "\\" + string.Format("{0:D}", DateTime.Now) + ".log";




            FileStream fs = new FileStream(strFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(DateTime.Now.ToString() + "\t" + str);
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
        static void Main(string[] args)
        {
            string[] logs = new string[8];
            string strFilePath = System.Environment.CurrentDirectory;
            PerformanceCounter[] counters = new PerformanceCounter[System.Environment.ProcessorCount];
            for (int i = 0; i < counters.Length; i++)
            {
                counters[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
            }


            Console.WriteLine("Start to write the logs ...");
            Console.WriteLine("Path:{0}", strFilePath);
            Console.WriteLine();
            for (int i = 0; i < counters.Length; i++)
            {
                float first = counters[i].NextValue();
            }
            System.Threading.Thread.Sleep(100);
            while (true)
            {
                for (int i = 0; i < counters.Length; i++)
                {
                    float f = counters[i].NextValue();
                    logs[i] = String.Format("{1:f}%\t", i, f);
                    Console.WriteLine("CPU-{0}: {1:f}%", i, f);
                }
                write_logs(logs[0] + logs[1] + logs[2] + logs[3]);
                Console.WriteLine();
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

运行结果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值