Created
June 13, 2012 09:59
-
-
Save richorama/2923167 to your computer and use it in GitHub Desktop.
Simple class to create and write to performance counters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
namespace Two10.Utils | |
{ | |
public class PerformanceMonitor : IDisposable | |
{ | |
string counterCategory = null; | |
string counterName = null; | |
Stopwatch watch = new Stopwatch(); | |
public PerformanceMonitor(string counterName, string counterCategory) | |
{ | |
this.watch.Start(); | |
this.counterName = counterName; | |
this.counterCategory = counterCategory; | |
} | |
private void WriteToCounter() | |
{ | |
try | |
{ | |
var pcTime = new PerformanceCounter(counterCategory, counterName, false); | |
var pcBase = new PerformanceCounter(counterCategory, counterName + "_base", false); | |
pcTime.IncrementBy(watch.ElapsedTicks); | |
pcBase.Increment(); | |
} | |
catch (Exception ex) | |
{ | |
Trace.WriteLine("Failed to write the performance counter {0}", counterName); | |
Trace.WriteLine(ex.ToString()); | |
} | |
} | |
public static void CreateCounters(string[] counterName, string counterCategory) | |
{ | |
try | |
{ | |
if (!PerformanceCounterCategory.Exists(counterCategory)) | |
{ | |
PerformanceCounterCategory.Create( | |
counterCategory, | |
"Custom Counters", | |
PerformanceCounterCategoryType.SingleInstance, | |
new CounterCreationDataCollection(CounterData(counterName).ToArray())); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Trace.WriteLine("Failed to create a performance counter in category '{0}'", counterCategory); | |
Trace.WriteLine(ex.ToString()); | |
} | |
} | |
private static IEnumerable<CounterCreationData> CounterData(string[] counterNames) | |
{ | |
foreach (var name in counterNames) | |
{ | |
yield return new CounterCreationData(name, "The elapsed time for " + name, PerformanceCounterType.AverageTimer32); | |
yield return new CounterCreationData(name + "_base", "The average base for " + name, PerformanceCounterType.AverageBase); | |
} | |
} | |
public void Dispose() | |
{ | |
watch.Stop(); | |
WriteToCounter(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment