10/23/11

C# Custom Performance Counters - First Performance Counter

Table of content:

I. C# Custom Performance Counters - Introduction
II. C# Custom Performance Counters - First Performance Counter

1. Creating a custom Performance Counters and Performance counters category.

You can create your own Performance category and Performance counters. To achieve this goal you can use Visual Studio tools, or .NET System.Diagnostics objects. In this post I’ll describe counters and category creation in a code using
using System.Diagnostics;

First of all you need to make a counters collection:

CounterCreationDataCollection collection = new CounterCreationDataCollection();

Then you need to create performance counter

CounterCreationData counter = new CounterCreationData();
counter.CounterName = "CountsPerSecond";
counter.CounterHelp = "CountsPerSecond";
counter.CounterType = PerformanceCounterType.RateOfCountsPerSecond32);
collection.Add(counter);

And place it into the category. As the category type you can use SingleInstance and MultiInstance. Multi instance is very usefull when dealing with multithread application. I will describe this in a next post.

if (!PerformanceCounterCategory.Exists("TestCategory"))
{
    PerformanceCounterCategory.Create("TestCategory", "This is test category", PerformanceCounterCategoryType.SingleInstance, collection);
}

Here is the complete code:

using System.Diagnostics;

namespace PerformaceCountersTest
{
    class Program
    {
        static void Main(string[] args)
        {
            CounterCreationDataCollection collection = new CounterCreationDataCollection();

            CounterCreationData counter = new CounterCreationData();
            counter.CounterName = "CountsPerSecond";
            counter.CounterHelp = "CountsPerSecond";
            counter.CounterType = PerformanceCounterType.RateOfCountsPerSecond32);
            collection.Add(counter);

            if (!PerformanceCounterCategory.Exists("TestCategory"))
            {
                 PerformanceCounterCategory.Create("TestCategory", "This is test category", PerformanceCounterCategoryType.SingleInstance, collection);
            }

        }
    }
}

When you run this code, you should see a new category with one counter in Windows performance tool:

If you don't know how to use Windows Performance tool, please look at the
C# Custom Performance Counters part I- Introduction


2. Using the performance counters in a code.

When we have defined the performance counters, it is time to use it.

First of all we need to create an instance of a counter and invoke method Increment()

PerformanceCounter countsPerSec = new PerformanceCounter("TestCategory", "CountsPerSecond", false);
countsPerSec.Increment();

Now it's time to test it:

using System.Diagnostics;

namespace PerformaceCountersTest
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformanceCounter countsPerSec = new PerformanceCounter("TestCategory", "CountsPerSecond", false);

            for (int i = 0; i < 100; i++)
            {
                countsPerSec.Increment();

                int sleep = 1000 - i * 10;
                Console.WriteLine(sleep);
                System.Threading.Thread.Sleep(sleep);
            }
        }
    }
}

If you setup the Performance tool to watch at your performance counter, you should get a result like this:
3. Test application.

Here is the test application code:

PerformanceCounterCreator class
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace PerformaceCountersTest
{
    class PerformanceCounterCreator
    {

        CounterCreationDataCollection collection = new CounterCreationDataCollection();

        public PerformanceCounterCreator()
        {
        }

        public void addPerformaceCounter(String name, String description, PerformanceCounterType type)
        {
            CounterCreationData counter = new CounterCreationData();
            counter.CounterName = name;
            counter.CounterHelp = description;
            counter.CounterType = type;
            collection.Add(counter);
        }

        public void createCategory(String categoryName,String categoryHelp, bool force)
        {
            if (PerformanceCounterCategory.Exists(categoryName))
            {
                if (force)
                {
                    PerformanceCounterCategory.Delete(categoryName);
                    PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, collection);
                }
            }
            else
                PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.SingleInstance, collection);

        }
    }
}

Main program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PerformaceCountersTest
{
    class Program
    {
        static void Main(string[] args)
        {
            PerformanceCounterCreator creator = new PerformanceCounterCreator();

            creator.addPerformaceCounter("CountsPerSecond", "CountsPerSecond", PerformanceCounterType.RateOfCountsPerSecond32);

            creator.createCategory("TestCategory","This is test category", true);

            //Create counter instance.
            PerformanceCounter countsPerSec = new PerformanceCounter("TestCategory", "CountsPerSecond", false);

            for (int i = 0; i < 100; i++)
            {
                countsPerSec.Increment();

                int sleep = 1000 - i * 10;
                Console.WriteLine(sleep);
                System.Threading.Thread.Sleep(sleep);
            }

        }
    }
}

4. References:
http://www.codeproject.com/KB/dotnet/perfcounter.aspx

http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountertype.aspx

C# Custom Performance Counters - Introduction

Table of content:

I. C# Custom Performance Counters - Introduction
II. C# Custom Performance Counters - First Performance Counter

1. Introduction

There is a moment in software engineer life when it is time to check application performance. At this certain point you will ask yourself “How can I do it?”. Answer is not simple because you can do it in a very different way. You can of course find any 3rd party application which will measure some things for you. You can make some kind of log file and insert some performance data to it, or you can use .NET System.Diagnostics namespace.

In this article I’ll focus on System.Diagnostics. I’m not saying it is the best approach, I’ll just describe some elements of it and you can decide if it suits your needs or not.

2. Where I can find Performance counters in Windows.

In Windows you can find some predefined performance counters. Just open Control Panel -> Administrative Tools -> Performance
There you can find some predefined counters on a chart.
You can of course add some additional predefined counters to the chart. Just press button marked red on the previous image and choose a Performance Object (performance category), some counters and instances.
If you would like to save some performance counters to look at the offline, you can save data to a file.

Just choose Performance Logs and Alerts -> Counter Logs.
Then press Action -> New Log Settings…  and type a name
In the next form
Press Add Counters and choose whatever you wish.


I’ve choose % Processor Time. Press Add and close when you finish.
On the Log Files sheet choose the log file type. I usually use the comma delimited file. It is easy to process in Excel for example. Set the interval on a General sheet and Schedule (if you like) to setup start and stop time for measurements.

Press OK to finish your job.

You should see the log file in location mentioned in “”Current log file name”.