下面是源码:
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);
}
}
}
}
运行结果如下: