如何使用PerfMon计数器记录C#中方法的平均执行时间?
到目前为止,我只发现了用于递增或递减PerfMon计数器的示例代码。
这是我曾经写的一些示例代码,用于实现这个功能。
首先,您需要指定并安装相关的性能计数器。您可以通过使用 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_; }
}
}
要写入性能计数器,可以按照以下方式进行:
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();
}
}