(来自:一个被遗忘的包子)
学习C#——性能计数器
写在前面:
作为Web应用开发前线的一枚小兵,每看到“性能”一词总有种要亮瞎眼的感觉,说到“性能”那就不能不提“数据”,在程序猿、攻城师中不是流行这样一句话吗?“无图无真相”,谁要说谁开发的应用性能有多好多好,那么要亮瞎我们这些小兵的眼睛,就不得不拿出“数据”来说话啦,显然,我们有一个能够为我们提供“数据”的工具是多么的重要。今天就来学习一下使用C#是如何实现计数器的?
简要Windows性能监视器:
打开Windows性能监视器的步骤如下:
开始→运行→perfmon→确定
在这里我们可以选择添加我们要监控的计数器,比如:cpu使用率、内存使用量等,作为asp.net攻城师我们还可以使用它来监控我们站点的请求队列、应道队列数量、请求总数等。比如我们要看可用内存的信息:
可用内存大小事实数据如下:
瞬间感觉到在微软怀抱下的孩纸好幸福有木有。好啦接下来我们来看看C#是如何调用它的,并且是如何自定义自己的计数器的呢?
C#如何调用Windows性能监视器获取数据
上代码:
using System; using System.Collections.Generic; using System.Text; //应引用此名门空间 using System.Diagnostics; using System.Threading; namespace Performance_Demo { class Class1 { static void Main(string[] arge) { //性能计数器组件类 PerformanceCounter cpu = new PerformanceCounter("Memory", "Available MBytes", ""); while (true) { Console.WriteLine("{0} MB",cpu.NextValue()); Thread.Sleep(1000); } } } }结果如下:
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Collections; namespace Performance_Demo { class Class2 { //我的队列 static Queue<int> myQueue = new Queue<int>(); //计数器实例 static PerformanceCounter counter1 = null; static void Main(string[] arge) { //计数器类型名称 string CategoryName = "a_yigebeiyiwangdebaozi"; //计数器名称 string CounterName = "a_yigebeiyiwangdebaozi_counter1"; if (PerformanceCounterCategory.Exists(CategoryName)) { PerformanceCounterCategory.Delete(CategoryName); } CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); //计数器 CounterCreationData ccd = new CounterCreationData(CounterName, "myCounter", PerformanceCounterType.NumberOfItems64); ccdc.Add(ccd); //使用PerformanceCounterCategory.Create创建一个计数器类别 PerformanceCounterCategory.Create(CategoryName, "", PerformanceCounterCategoryType.MultiInstance, ccdc); //初始化计数器实例 counter1 = new PerformanceCounter(); counter1.CategoryName = CategoryName; counter1.CounterName = CounterName; counter1.InstanceName = "myCounter1"; counter1.InstanceLifetime = PerformanceCounterInstanceLifetime.Process; counter1.ReadOnly = false; counter1.RawValue = 0; while (true) { EnqueueQueue(); System.Threading.Thread.Sleep(1000); DequeueQueue(); } } static void EnqueueQueue() { int C = new Random().Next(10); for (int i = 0; i < C; i++) { myQueue.Enqueue(i); //计数器加一 counter1.Increment(); } } static void DequeueQueue() { int C = new Random().Next(20); for (int i = 0; i < C; i++) { if (myQueue.Count == 0) break; myQueue.Dequeue(); //计数器减一 counter1.Decrement(); } } } }我们先在性能监视器中找到我们的计数器如下: