我试图设置一个PerformanceCounter
来衡量某个方法的平均执行时间。我试过阅读AverageTimer32
,我已经看了很多例子,但我似乎无法做到。关于AverageTimer32 PerformanceCounter的困惑
我设置的类别
CounterCreationDataCollection CCDC = new CounterCreationDataCollection();
// Add the counter.
CounterCreationData averageTimer32 = new CounterCreationData();
averageTimer32.CounterType = PerformanceCounterType.AverageTimer32;
averageTimer32.CounterName = counterName;
CCDC.Add(averageTimer32);
// Add the base counter.
CounterCreationData averageTimer32Base = new CounterCreationData();
averageTimer32Base.CounterType = PerformanceCounterType.AverageBase;
averageTimer32Base.CounterName = baseCounterName;
CCDC.Add(averageTimer32Base);
// Create the category.
PerformanceCounterCategory.Create(categoryName, "Demonstrates usage of the AverageTimer32 performance counter type", PerformanceCounterCategoryType.SingleInstance, CCDC);
然后,我创建了柜台
PC = new PerformanceCounter(categoryName, counterName, false);
BPC = new PerformanceCounter(categoryName, baseCounterName, false);
PC.RawValue = 0;
BPC.RawValue = 0;
最后我我的每一个方法被调用
private void TheMethodIWantToMeasure() {
Stopwatch stopwatch = Stopwatch.StartNew();
// Fake work that take ~50ms
Thread.Sleep(50 + random.Next(-10, 10));
stopwatch.Stop();
PC.IncrementBy(stopwatch.ElapsedTicks);
BPC.Increment();
}
否则,如时间记录经过的时间这最终会导致性能监视器看起来像这样。我得到尖峰,而不是50毫秒的连续曲线:
我误解了AverageTimer32
?我已经阅读过,但有点令人困惑。但是,我看过几个例子和我一样,所以我猜它应该可以工作。什么可能是我只有尖峰的原因?
编辑 这可能是值得一提的是TheMethodIWantToMeasure
只叫每5秒〜,我才意识到,我让每个〜秒杀第5秒。但我不明白如果AverageTimer32
使用公式((N 1 -N 0)/ F)/(B 1 -B 0),结果会如何影响结果。它不应该取决于我为N和B存储值的频率?