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.
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.
Take a look at the different PerformanceCounterTypes. There are several types for calculating average time or count. You will also find some examples.
Hope this helps.
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();
}
}