C# - Performance Counters

Reading performance counters (in C#) require the use of the PerformanceCounter class to read existing predefined or custom counters. The PerformanceCounter class is included in the System.Diagnostic namespace, and provides accessibility to several counters.

The most common counters include Processor, Memory, and Network Utilization.

// CPU Processor Time (in %)
PerformanceCounter cpuCounter = 
    new PerformanceCounter("Processor", "% Processor Time", "_Total");
Console.WriteLine("Current CPU: {0}", cpuCounter.NextValue() +"%");

// Memory Available (in MB)
PerformanceCounter ramCounter = 
    new PerformanceCounter("Memory", "Available MBytes", string.Empty);                        
Console.WriteLine("RAM Available: {0}", ramCounter.NextValue()+"MB");

// Network Utilization (in Bytes/Sec)
PerformanceCounterCategory category = 
    new PerformanceCounterCategory("Network Interface");
String[] instanceName = category.GetInstanceNames();
foreach (string ns in instanceName)
{
    PerformanceCounter netSentCounter = 
        new PerformanceCounter("Network Interface", "Bytes Received/sec", ns);
    PerformanceCounter netRecCounter = 
        new PerformanceCounter("Network Interface", "Bytes Sent/sec", ns);
    Console.WriteLine("Network Interface: {0}", ns);
    Console.WriteLine("Network Usage (Sent): {0}",
        netSentCounter.NextValue()+" Bytes/s");
    Console.WriteLine("Network Usage (Received): {0}",
        netRecCounter.NextValue()+" Bytes/s");
}

Comments

Popular posts from this blog

C# - ListView Item Spacing (Padding)

C# / SQL - Performing Distributed Transactions

IIS / ASP.NET - Disabling Compatibility Mode/View (Internet Explorer)