Creating a PerfMon counter to record an average per call (C#)

Justin picture Justin · Sep 11, 2009 · Viewed 40.7k times · Source

How can I use PerfMon counters to record the average execution time of a method in C#?

So far I've only found sample code to incrememnt or decrement a PerfMon counter.

Answer

Mark Seemann picture Mark Seemann · Sep 11, 2009

Here's some sample code I once wrote to do exactly that.

First, you need to specify and install the performance counters in question. You can do this by using an Installer:

public class CreditPerformanceMonitorInstaller : Installer
{
    private PerformanceCounterInstaller counterInstaller_;

    public CreditPerformanceMonitorInstaller()
    {
        this.counterInstaller_ = new PerformanceCounterInstaller();
        this.counterInstaller_.CategoryName = CreditPerformanceCounter.CategoryName;
        this.counterInstaller_.CategoryType = PerformanceCounterCategoryType.SingleInstance;

        CounterCreationData transferAverageData = new CounterCreationData();
        transferAverageData.CounterName = CreditPerformanceCounter.AverageTransferTimeCounterName;
        transferAverageData.CounterHelp = "Reports the average execution time of transfer operations";
        transferAverageData.CounterType = PerformanceCounterType.AverageTimer32;
        this.counterInstaller_.Counters.Add(transferAverageData);

        CounterCreationData transferAverageBaseData = new CounterCreationData();
        transferAverageBaseData.CounterName = CreditPerformanceCounter.AverageTransferTimeBaseCounterName;
        transferAverageBaseData.CounterHelp = "Base for average transfer time counter";
        transferAverageBaseData.CounterType = PerformanceCounterType.AverageBase;
        this.counterInstaller_.Counters.Add(transferAverageBaseData);

        this.Installers.Add(this.counterInstaller_);
    }

    public Installer PerformanceCounterInstaller
    {
        get { return this.counterInstaller_; }
    }
}

To write to the performance counter, you can do it like this:

public void RecordTransfer(long elapsedTicks)
{
    using (PerformanceCounter averageTransferTimeCounter = new PerformanceCounter(),
        averageTransferTimeBaseCounter = new PerformanceCounter())
    {
        averageTransferTimeCounter.CategoryName = CreditPerformanceCounter.CategoryName;
        averageTransferTimeCounter.CounterName = CreditPerformanceCounter.AverageTransferTimeCounterName;
        averageTransferTimeCounter.ReadOnly = false;

        averageTransferTimeBaseCounter.CategoryName = CreditPerformanceCounter.CategoryName;
        averageTransferTimeBaseCounter.CounterName = CreditPerformanceCounter.AverageTransferTimeBaseCounterName;
        averageTransferTimeBaseCounter.ReadOnly = false;

        averageTransferTimeCounter.IncrementBy(elapsedTicks);
        averageTransferTimeBaseCounter.Increment();
    }
}