PerformanceCounter 性能计数器的使用

来源:互联网 发布:java获取list泛型类型 编辑:程序博客网 时间:2024/05/19 12:15

1:获取性能计数器类别列表

public static void GetCategoryNameList(){        PerformanceCounterCategory[] myCat2;        myCat2 = PerformanceCounterCategory.GetCategories();        for (int i = 0; i < myCat2.Length; i++)        {                Console.WriteLine(myCat2[i].CategoryName.ToString());        }}

2:获取性能计数器类别下的实例的名称实例下的性能计数器的名称
public static void GetInstanceNameListANDCounterNameList(string CategoryName){        string[] instanceNames;        ArrayList counters = new ArrayList();        PerformanceCounterCategory mycat = new PerformanceCounterCategory(CategoryName);        try        {                instanceNames = mycat.GetInstanceNames();                if (instanceNames.Length == 0)                {                        counters.AddRange(mycat.GetCounters());                }                else                {                        for (int i = 0; i < instanceNames.Length; i++)                        {                                counters.AddRange(mycat.GetCounters(instanceNames[i]));                        }                }                for (int i = 0; i < instanceNames.Length; i++)                {                        Console.WriteLine(instanceNames[i]);                }                Console.WriteLine("******************************");                foreach (PerformanceCounter counter in counters)                {                        Console.WriteLine(counter.CounterName);                }        }        catch (Exception)        {                Console.WriteLine("Unable to list the counters for this category");        }}


3:根据categoryName,counterName,instanceName获得性能情况显示
private static void PerformanceCounterFun(string CategoryName, string InstanceName, string CounterName){        PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);        while (true)        {                Thread.Sleep(1000);                 float cpuLoad = pc.NextValue();                Console.WriteLine("CPU load = " + cpuLoad + " %.");        }}


4:调用方法3显示cpu使用率
PerformanceCounterFun("Processor", "_Total", "% Processor Time");

0 0