Use your own performance counters

Create and use your own performance counters to see how you program is doing in performancetests, stresstests, production, …
First register the performance counters. This is done with a PerformanceCounterCategory that contains the CounterCreationData objects for the performance counters. Be sure to check it doesn’t already exists or an exception is thrown.

// create performance counters if not already existing
if (PerformanceCounterCategory.Exists(CATEGORY) == false)
    var counters = new CounterCreationDataCollection();
    // create reads per second performance counter
    var reads = new CounterCreationData();
    reads.CounterName = "# reads per second";
    reads.CounterHelp = "Number of reads per second";
    reads.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
    // create writes per second performance counter
    var writes = new CounterCreationData();
    writes.CounterName = "# writes per second";
    writes.CounterHelp = "Number of writes per second";
    writes.CounterType = PerformanceCounterType.RateOfCountsPerSecond32;
    // create number of exceptions performance counter
    var fails = new CounterCreationData();
    fails.CounterName = "# failed actions";
    fails.CounterHelp = "Number of failed actions";
    fails.CounterType = PerformanceCounterType.NumberOfItems32;
    // create new category with the counters above
    PerformanceCounterCategory.Create(CATEGORY, "My Project Category", PerformanceCounterCategoryType.SingleInstance, counters);

After the category is created you can use the PerformanceCounters in your code. You don’t need to create a new instance of the PerformanceCounter every time it needs to be incremented. I always create a variable at the start of a thread and use it in that thread only.

var reads = new PerformanceCounter(CATEGORY, "# reads per second", false);
// register a read with the performance counter

Clean up at the end of your program, the code below will remove the performance counters again.

// clean up the performance counters at the end of your program
if (PerformanceCounterCategory.Exists(CATEGORY) == true)

If you don’t see any value changes in the Performance Monitor try closing and opening the Performance Monitor.

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Test and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.