Introduction

Setting up and using Performance Counters with the .NET API requires a bit of setup and configuration. This article presents a generalized code block which can be used in a common scenario for simple performance benchmarking.

Background

Finding how fast your application runs would be tricky business lacking any way to measure it. In Windows, we've got the built-in Performance Counters which can easily time operations and gather statistics about your software while it executes.

As some superhero may have mentioned, "With great flexibility comes great complexity", so we'll look at a way to wrap a common usage with a reusable code block.

Using the Code

My first annoyance with the performance counter classes in .NET is the need to initialize two different classes for a single counter - one for creating it and another for interacting with the values. Since they have several overlapping properties which, by the way, need to be exactly the same or if they won't work, the definitions can be easily coupled:

Notice that the OperationCompleted method has the duty of incrementing all of the counters once an operation has been completed. Now, how is all of this wired to something we'd want to actually measure? First, I'll define an interface which exposes an OpeartionCompleted event that will be raised by the object when it has something to measure.

The code to configure and use OperationPerformanceCounter is quite simple. First, an object implementing IOperationCompletable. Here is a demonstration - this object can raise events for two operations that we're interested in - FastOp and SlowOp.

Running this will add the performance counters and record the following data - here are the resulting graphs created while comparing "Operations per Second" and "Average Duration" for "FastOp" and "SlowOp".