看到《编程之美》上讲的让CPU使用记录曲线显示成直线或者正弦曲线,除了书中已述的代码,自己又动手编了一个。 using System;using System.Collections.Generic;using System.Text;using System.Diagnostics; namespace cpuplay{ class Program { static void Main(string[] args) { Play(); } static void Play() { ////list the categories //PerformanceCounterCategory[] PCCs = PerformanceCounterCategory.GetCategories(); //foreach (PerformanceCounterCategory pcc in PCCs) // TextOut(f1, pcc.CategoryName); ////Instantialize a specific category //PerformanceCounterCategory counterCategory = new PerformanceCounterCategory("Processor"); //////list instances for this category //string[] instances = counterCategory.GetInstanceNames(); //foreach (string s in instances) // TextOut(counterCategory.CategoryName + ".instance.txt", s); ////list the counters for this category //PerformanceCounter[] PCs = counterCategory.GetCounters("_Total"); //foreach (PerformanceCounter pc in PCs) // TextOut(counterCategory.CategoryName + ".name.txt", pc.CounterName); //choose a counter PerformanceCounter counter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); ////just have a look at some value samples //for (int i = 0; i <10; i++) //{ // TextOut("p.txt", counter.NextValue() + ", "+ counter.RawValue); // System.Threading.Thread.Sleep(20); //} ////now we can draw a 50 percent usage line //float level = 50;// 0~100 //while (true) //{ // if (counter.NextValue() >level) // System.Threading.Thread.Sleep(20); //} //draw a sine curve while (true) { for (int i = 0; i <200; i++) { int time = System.Environment.TickCount; int d = (int)(50 + 50 * Math.Sin(0.01 * i * Math.PI)); while (System.Environment.TickCount - time <2*d) { ; } System.Threading.Thread.Sleep(200 - d); } } } static string f1 = "CounterCategories.txt"; static void TextOut(string fileloc,string s) { System.IO.StreamWriter sw = new System.IO.StreamWriter(fileloc,true); sw.WriteLine(s); sw.Flush(); sw.Close(); } }} 画直线的比较简单,还可以调整参数,counter.NextValue返回的是一个0~100间的数,表示比率。 CPU50%比率曲线如下: 正弦曲线的也不复杂,道理是差不多的,最后在单核机器上给出的图像是: 双核机器上先获取当前进程是在哪个CPU上运行,然后把_Total改成0或1就可以了。 有些参数开始不知道是什么,所以添加了注释中的代码,把各种能用的参数都输出来看一看。譬如cpu的performanceCounter实例分为_Total,0,如果是双核的,就是_Total,0,1。 利用visual studio的对象浏览器,可以很方便的查找到那些有用的函数以及使用方法。 有两点尚不完善:一是波峰未到顶,虽然程序是不结束的死循环,但CPU使用率仍然不会到100%,因为循环中添加的是一个空语句。第二点是曲线下摆不够圆滑,多次调整了时间间隔的参数,仍然得不到满意的形状,时间原因,不再深究。