创建PerfMon计数器以记录每次调用的平均值(C#)

时间:2009-09-11 08:45:45

标签: c# perfmon

如何使用PerfMon计数器记录C#中方法的平均执行时间?

到目前为止,我只找到了增加或减少PerfMon计数器的示例代码。

2 个答案:

答案 0 :(得分:40)

以下是我曾写过的一些示例代码。

首先,您需要指定并安装有问题的性能计数器。您可以使用安装程序执行此操作:

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();
    }
}

答案 1 :(得分:4)

看一下不同的PerformanceCounterTypes。 计算平均时间或计数有几种类型。你也会找到一些例子。

希望这有帮助。