我正在尝试设置一个PerformanceCounter
来测量某个方法的平均执行时间。我已经尝试阅读了一些有关AverageTimer32
的文档,并查看了很多示例,但似乎始终无法正确设置。
我已经设置好了分类。
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毫秒的连续曲线:![Picture](https://istack.dev59.com/9WkkO.webp)
AverageTimer32
?我已经阅读了相关信息,但它有点令人困惑。然而,我已经看到做的几乎和我一样的实例,所以我想这应该可以工作。我只得到尖峰的原因是什么?
编辑
值得一提的是,TheMethodIWantToMeasure
每5秒钟只会调用一次,我刚意识到我每5秒钟就会受到这个尖峰的干扰。但我不明白如果AverageTimer32
使用公式((N 1 - N 0) / F) / (B 1 - B 0),这如何影响结果。它不应该取决于我多久存储N和B的值吗?