Stephen Mitchell
4/17/2018 - 4:56 PM

Linq Pad CPU usage C# program sample

Linq Pad CPU usage C# program sample

void Main()
{
	var instanceName = "LINQPad";
	var counterCollectionInterval = TimeSpan.FromSeconds(1);
	
	var continueCollectingTimeFrame = TimeSpan.FromSeconds(10);
	
	var counters = from performanceCounterDefinition in PerformanceCounterRepository.GetPerfCounters
			from counterName in performanceCounterDefinition.Counters
			select new {
						performanceCounterDefinition.CategoryName, 
						counterName, 
						instanceName = performanceCounterDefinition.InstanceUsage(instanceName)
						};


	foreach(var counter in counters)
	{
		var timerObject = new TimedPerfCounter(counter.CategoryName, counter.counterName, counter.instanceName);
	
		System.Timers.Timer aTimer = new System.Timers.Timer();
		aTimer.Elapsed += new ElapsedEventHandler(timerObject.OnTimer);
		aTimer.Interval = counterCollectionInterval.TotalMilliseconds;
		aTimer.Enabled = true;
		aTimer.AutoReset = true;
	}
	
	Console.WriteLine(string.Format("reporting performance counter for the next {0} seconds",continueCollectingTimeFrame.TotalSeconds));
   	Thread.Sleep(continueCollectingTimeFrame);
   	return ;	
}

// Define other methods and classes here
public struct TimedPerfCounter
{
private readonly string instanceName;
private readonly PerformanceCounter counter;

public TimedPerfCounter(string objectName, string counterName, string instanceName)
{
 	try
   	{
		if ( !PerformanceCounterCategory.Exists(objectName) )
	  		throw new ArgumentException("Object {0} does not exist", objectName);		 	  
   	}
   	catch (UnauthorizedAccessException ex)
   	{
		Console.WriteLine("You are not authorized to access this information.");
	  	Console.Write("If you are using Windows Vista, run the application with ");
	  	Console.WriteLine("administrative privileges.");
	  	Console.WriteLine(ex.Message);
	  	throw;
   	}

   	if (!PerformanceCounterCategory.CounterExists(counterName, objectName) )
   	  	throw new ArgumentException("Counter {0} does not exist", counterName);
	
	this.counter = new PerformanceCounter(objectName, counterName, instanceName);
	this.instanceName = string.Format("{0} {1} {2}", counter.CategoryName, counter.CounterName, counter.InstanceName);
}

public void OnTimer(Object source, ElapsedEventArgs e)
   {
	  try 
	  {
		 Console.WriteLine("{0}: {1} ", instanceName, counter.NextValue().ToString("f"));
	  } 
	  catch(Exception ex)
	  {
		 if (ex as InvalidOperationException != null)
		 {
			Console.WriteLine("Instance '{0}' does not exist", instanceName);
			Console.WriteLine(ex);
			return;
		 }
		 else
		 {
			Console.WriteLine(ex);
			Console.WriteLine("Unknown exception... ('q' to quit)");
			return;
		 }
	  }
   }
}

public class PerformanceCounterDefinition
{
	public string CategoryName { get; set; }
	public Func<string,string> InstanceUsage { get; set; }
	public string[] Counters { get; set; }
}

public class PerformanceCounterRepository
{
	public static PerformanceCounterDefinition[] GetPerfCounters 
	{ 
		get {
		return new [] {
					new PerformanceCounterDefinition { 
							CategoryName = ".NET CLR Memory", 
						 	Counters = new []{
								"# Bytes in all Heaps",
								"# Gen 0 Collections",
								"# Gen 1 Collections",
								"# Gen 2 Collections",
								"# Induced GC",
								"# Total committed Bytes",
								"# Total reserved Bytes",
								"% Time in GC",
								"Allocated Bytes/sec",
								"Gen 0 heap size",
								"Gen 0 Promoted Bytes/Sec",
								"Gen 1 heap size",
								"Gen 1 Promoted Bytes/Sec",
								"Gen 2 heap size",
								"Large Object Heap size",
								"Promoted Finalization-Memory from Gen 0",
								"Promoted Finalization-Memory from Gen 1",
								"Promoted Memory from Gen 0",
								"Promoted Memory from Gen 1"
							},
							InstanceUsage = (string counterInstanceName) => {return counterInstanceName;}
					},
					new PerformanceCounterDefinition{ 
							CategoryName = ".NET CLR Networking", 
							Counters = new []{
								"Datagrams Received",
								"Datagrams Sent",
								"Bytes Received",
								"Bytes Sent",
							},
							InstanceUsage = (string counterInstanceName) => {return counterInstanceName;}
					},
					new PerformanceCounterDefinition{ 
							CategoryName = "Processor", 
							Counters = new []{
								"% Processor Time",
							},
							InstanceUsage = (string counterInstanceName) => {return "_Total";}
					},
					new PerformanceCounterDefinition{
							CategoryName = "System",
							Counters = new []{
								"Context Switches/sec",
								"Processor Queue Length",
								"Threads",
							},
							InstanceUsage = (string counterInstanceName) => {return null;}
					}
				};
		}
	}
}