今天在网上看到一段比较好玩的代码,用来显示本地计算机CPU的使用情况,整理到本机如下:
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private const string CategoryName = "Processor";
private const string CounterName = "% Processor Time";
private const string InstanceName = "_Total";
private static void OutPut(string txt)
{
Console.WriteLine(txt);
}
[STAThread]
public static void Main()
{
PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);
OutPut("----------------------------开始创造性能计数器----------------------------");
OutPut("计数器类型:" + pc.CounterType);
OutPut("计数器的说明:" + pc.CounterHelp);
OutPut("开始输出:");
while (true)
{
Thread.Sleep(1000);
float cpuLoad = pc.NextValue();
OutPut("CPU 耗用:" + cpuLoad + "%");
}
}
}
}
直接运行程序,对比控制台输出的结果与计算机的Windows任务管理器中显示的CPU使用值,会发现原来Windows任务管理器显示的值是CPU使用率的四舍五入的结果。有兴趣的朋友可以自己复制代码试试看啦。la<