當我執行以下程序並查看性能計數器時,結果對我來說沒有意義。當我期望〜0.1或〜100時,平均值爲零,最小/最大值爲〜0.4。如何在System.Diagnostics.Stopwatch中使用AverageTimer32和AverageBase性能計數器?
我的問題是什麼?
代碼
class Program
{
const string CategoryName = "____Test Category";
const string CounterName = "Average Operation Time";
const string BaseCounterName = "Average Operation Time Base";
static void Main(string[] args)
{
if (PerformanceCounterCategory.Exists(CategoryName))
PerformanceCounterCategory.Delete(CategoryName);
var counterDataCollection = new CounterCreationDataCollection();
var avgOpTimeCounter = new CounterCreationData()
{
CounterName = CounterName,
CounterHelp = "Average Operation Time Help",
CounterType = PerformanceCounterType.AverageTimer32
};
counterDataCollection.Add(avgOpTimeCounter);
var avgOpTimeBaseCounter = new CounterCreationData()
{
CounterName = BaseCounterName,
CounterHelp = "Average Operation Time Base Help",
CounterType = PerformanceCounterType.AverageBase
};
counterDataCollection.Add(avgOpTimeBaseCounter);
PerformanceCounterCategory.Create(CategoryName, "Test Perf Counters", PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
var counter = new PerformanceCounter(CategoryName, CounterName, false);
var baseCounter = new PerformanceCounter(CategoryName, BaseCounterName, false);
for (int i = 0; i < 500; i++)
{
var sw = Stopwatch.StartNew();
Thread.Sleep(100);
sw.Stop();
Console.WriteLine(string.Format("t({0}) ms({1})", sw.Elapsed.Ticks, sw.Elapsed.TotalMilliseconds));
counter.IncrementBy(sw.Elapsed.Ticks);
baseCounter.Increment();
}
Console.Read();
}
}
性能計數器截圖 Performance Counter Screenshot http://friendfeed-media.com/50028bb6a0016931a3af5122774b56f93741bb5c
爲什麼你需要鑄造選中((Int32)已.. )? performanceCounterTicks被評估爲long,所有的值實際上都是很長的數字。 – 2013-01-02 15:25:19
@DavideIcardi:謝謝,你說得對'IncrementBy'方法的簽名接受'Int64',所以不需要執行強制轉換。我已經從代碼中刪除了演員。 – 2013-01-02 16:18:34
不錯!正確的我正在尋找! – vtortola 2014-04-24 21:31:05