如何使用 PerfMon 计数器记录 C# 中方法的平均执行时间?
到目前为止,我只找到了增加或减少 PerfMon 计数器的示例代码。
这是我曾经写过的一些示例代码来做到这一点。
首先,您需要指定并安装有问题的性能计数器。您可以使用安装程序执行此操作:
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();
}
}
看看不同的PerformanceCounterTypes。有几种计算平均时间或计数的类型。您还将找到一些示例。
希望这可以帮助。