我試圖設置一個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存儲值的頻率?