我正在尝试设置一个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 毫秒左右得到尖峰而不是连续曲线:
我误解了AverageTimer32
吗?我读过它,但它有点令人困惑。但是,我已经看到示例与我做几乎相同的事情,所以我猜它应该可以工作。我只得到尖峰的原因可能是什么?
编辑
可能值得一提的TheMethodIWantToMeasure
是,每隔约 5 秒调用一次,我刚刚意识到我每隔约 5 秒就会收到一次尖峰信号。但我不明白如果AverageTimer32
使用公式 ((N 1 -N 0)/F)/(B 1 -B 0) 会如何影响结果。它不应该取决于我存储 N 和 B 值的频率吗?