使用性能计数器,获取系统性能数据

  在代码调试过程中,我们往往都需要去观察程序的状况和计算机的状态,以评估程序对计算机性能的影响。那如何程序或者计算机的性能数据?

1、Process 数据

  Process的数据可以看进程的相关使用情况,通过Process.GetCurrentProcess()获得当前程序的Process,然后打印相关数据。

Dictionary<string, string> DicPerfm = new Dictionary<string, string>
{
    { "ProcessName", ps.ProcessName },
    { "TotalProcessorTime(ms)", ps.TotalProcessorTime.TotalMilliseconds.ToString() + "ms" },
    { "UserProcessorTime(ms)", ps.UserProcessorTime.TotalMilliseconds.ToString() + "ms" },
    { "Kernal Time(ms)", (ps.TotalProcessorTime.TotalMilliseconds - ps.UserProcessorTime.TotalMilliseconds).ToString() + "ms" },
    { "Physical Memory Working Set", (ps.WorkingSet64 / 1024 / 1024).ToString() + "MB" },
    { "Virtual Memory Virtual Size", (ps.VirtualMemorySize64 / 1024 / 1024).ToString() + "MB" }
};

foreach (var item in DicPerfm)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

2、PerformanceCounter 性能计数器

  PerformanceCounter 是C#提供的一个可以监控并获取计算机某些性能的类,诸如网络速度、硬盘读写速度、内存使用、计算机CPU温度等等。

  构造一个PerformanceCounter对象,并对CategoryName、CounterName 、InstanceName 分别进行赋值,就可以监控计算机的某种数据。其NextValue()方法返回当前计数结果值。

  如果对不知道有哪些类别,可以使用PerformanceCounterCategory获得相关类别和计数器实例:

PerformanceCounterCategory[] pcc = PerformanceCounterCategory.GetCategories();

StringBuilder sb = new StringBuilder();
for (int i = 0; i < pcc.Length; i++)
{
    sb.Remove(0, sb.Length);
    sb.Append("CategoryName:" + pcc[i].CategoryName + "\r\n");
    sb.Append("MachineName:" + pcc[i].MachineName + "\r\n");
    string[] instanceNames = pcc[i].GetInstanceNames();
    for (int j = 0; j < instanceNames.Length; j++)
    {

        sb.Append("**** Instance Name **********\r\n");
        sb.Append("InstanceName:" + instanceNames[j] + "\r\n");
        try
        {
            PerformanceCounter[] counters = pcc[i].GetCounters(instanceNames[j]);
            for (int k = 0; k < counters.Length; k++)
            {
                sb.Append("CounterName:" + counters[k].CounterName + "\r\n");
            }
        }
        catch (Exception)
        { }
        sb.Append("**************************************************\r\n");
    }
    Console.WriteLine(sb.ToString());
}

3、获取CPU、内存、硬盘读写速率

  使用PerformanceCounter统计CPU、内存、硬盘使用情况:

  首先声明性能计数器实例,并初始化实例数据:

static private PerformanceCounter cpuPerformanceCounter = new PerformanceCounter();//CPU的使用监控
static private PerformanceCounter memoryPerformanceCounter = new PerformanceCounter();//内存使用监控
static private PerformanceCounter diskReadsPerformanceCounter = new PerformanceCounter();//硬盘读取速度监控
static private PerformanceCounter diskWritesPerformanceCounter = new PerformanceCounter();//硬盘写入速度监控
static private PerformanceCounter diskTransfersPerformanceCounter = new PerformanceCounter();//硬盘传输速度监控
//初始化性能监控器
private static void InitPerformanceCounters()
{
    cpuPerformanceCounter.CategoryName = "Processor";
    cpuPerformanceCounter.CounterName = "% Processor Time";
    cpuPerformanceCounter.InstanceName = "_Total";

    memoryPerformanceCounter.CategoryName = "Memory";
    memoryPerformanceCounter.CounterName = "Available MBytes";

    diskReadsPerformanceCounter.CategoryName = "PhysicalDisk";
    diskReadsPerformanceCounter.CounterName = "Disk Reads/sec";
    diskReadsPerformanceCounter.InstanceName = "_Total";

    diskWritesPerformanceCounter.CategoryName = "PhysicalDisk";
    diskWritesPerformanceCounter.CounterName = "Disk Writes/sec";
    diskWritesPerformanceCounter.InstanceName = "_Total";

    diskTransfersPerformanceCounter.CategoryName = "PhysicalDisk";
    diskTransfersPerformanceCounter.CounterName = "Disk Transfers/sec";
    diskTransfersPerformanceCounter.InstanceName = "_Total";
}

  在输出时,需要调用NextValue()方法,可以获得计数周期内的数据:

//打印性能
static private void PrintPerformanceData()
{
    string currentCpuUsage = "CPU Usage : " + cpuPerformanceCounter.NextValue().ToString() + " %" + Environment.NewLine;
    string currentMemoryUsage = "Memory Usage : " + memoryPerformanceCounter.NextValue().ToString() + " Mb" + Environment.NewLine;
    string currentDiskReads = "Disk reads / sec : " + diskReadsPerformanceCounter.NextValue().ToString() + Environment.NewLine;
    string currentDiskWrites = "Disk writes / sec : " + diskWritesPerformanceCounter.NextValue().ToString() + Environment.NewLine;
    string currentDiskTransfers = "Disk transfers / sec : " + diskTransfersPerformanceCounter.NextValue().ToString() + Environment.NewLine;

    Console.Write("{0}{1}{2}{3}{4}", currentCpuUsage, currentMemoryUsage, currentDiskReads, currentDiskWrites, currentDiskTransfers);
}

4、获取实时网络速度

public class NetworkAdapter
{
    public string Name { get; private set; }
    public NetworkAdapter(string name)
    {
        Name = name;
        PerformanceCounter bandwidth = new PerformanceCounter("Network Interface", "Current Bandwidth", name);
        receive = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);
        send = new PerformanceCounter("Network Interface", "Bytes Sent/sec", name);
        BandwidthKbps = bandwidth.NextValue() / 1000 ;
    }

    PerformanceCounter receive;
    public double DownloadSpeedKbps
    {
        get
        {
            return receive.NextValue() / 1000;//bps=>kpbs
        }
    }


    PerformanceCounter send;
    public double UploadSpeedKbps
    {
        get
        {
            return send.NextValue() / 1000;//bps=>kpbs
        }
    }

    public float BandwidthKbps { get; private set; }//网络带宽
}


private static List<NetworkAdapter> GetNetworkAdapters()
{
    //方法1
    //NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces();
    //List<string> lstAdapters = new List<string>();
    //foreach (NetworkInterface adapter in networks)
    //{
    //    lstAdapters.Add(adapter.Description);
    //}

    //方式二
    //List<NetworkAdapter> networkAdapters = new List<NetworkAdapter>();
    //PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
    //foreach (string name in category.GetInstanceNames())
    //{
    //    // This one exists on every computer.
    //    if (name.Contains("Loopback Interface"))
    //    {
    //        continue;
    //    }
    //    networkAdapters.Add(new NetworkAdapter(name));
    //}

    //方式三
    List<NetworkAdapter> networkAdapters = new List<NetworkAdapter>();
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus=2");
    ManagementObjectCollection adapterObjects = searcher.Get();
    foreach (ManagementObject adapterObject in adapterObjects)
    {
        string name = adapterObject["Name"].ToString();
        networkAdapters.Add(new NetworkAdapter(name));
    }

    return networkAdapters;
}



public void PrintNetworkSpeed()
{
    List<NetworkAdapter> adapters = GetNetworkAdapters();
    foreach (NetworkAdapter adapter in adapters)
    {
        Console.WriteLine("Adapter Name: {0}", adapter.Name);
        Console.WriteLine(String.Format("Download: {0:n} Kbps upload: {1:n} Kbps", adapter.DownloadSpeedKbps, adapter.UploadSpeedKbps));
    }
}

 

posted @ 2021-09-12 20:27  一只独行的猿  阅读(549)  评论(0编辑  收藏  举报