gpt4 book ai didi

c# - 创建一个 PerfMon 计数器来记录每次调用的平均值 (C#)

转载 作者:IT王子 更新时间:2023-10-29 04:29:20 24 4
gpt4 key购买 nike

如何使用 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();
}
}

关于c# - 创建一个 PerfMon 计数器来记录每次调用的平均值 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1409762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com