如何在System.Diagnostics.Stopwatch中使用AverageTimer32和AverageBase性能计数器?当我执行以下程序并查看性能计数器时,结果对我来说没有意义。平均值为零,当我期望~0.1或~100时,最小/最大值为~0.4。我的问题是什么?conststringCounterName="平均操作时间";conststringBaseCounterName="平均操作时基";staticvoidMain(string[]args){if(PerformanceCounterCategory.Exists(CategoryName))PerformanceCounterCategory.Delete(CategoryName);varcounterDataCollection=newCounterCreationDataCollection();varavgOpTimeCounter=newCounterCreationData(){CounterName=CounterName,CounterHelp="平均操作时间帮助",CounterType=PerformanceCounterType.AverageTimer32};counterDataCollection.Add(avgOpTimeCounter);varavgOpTimeBaseCounter=newCounterCreationData(){CounterName=BaseCounterName,CounterHelp="AverageOperationTimeBaseHelp",CounterType=PerformanceCounterType.AverageBase};counterDataCollection.Add(avgOpTimeBaseCounter);PerformanceCounterCategory.Create(CategoryName,"测试性能计数器",PerformanceCounterCategoryType.SingleInstance,counterDataCollection);varcounter=newPerformanceCounter(CategoryName,CounterName,false);varbaseCounter=newPerformanceCounter(CategoryName,BaseCounterName,false);for(inti=0;i<500;i++){varsw=秒表。开始新();线程.睡眠(100);sw.停止();Console.WriteLine(string.Format("t({0})ms({1})",sw.Elapsed.Ticks,sw.Elapsed.TotalMilliseconds));counter.IncrementBy(sw.Elapsed.Ticks);baseCounter.Increment();}控制台.Read();.DiagnosticsAPI包含一个非常微妙的混淆来源:System.Diagnostics'ticks'与DateTime或TimeSpan'ticks'不同!如果您使用StopWatch.ElapsedTicks而不是StopWatch.Elapsed.Ticks,它应该可以工作该文档有关于此的更多信息。MarkSeemann解释了问题中混乱的根源,但我想提供一些额外的信息。如果要从TimeSpan而不是Stopwatch设置AverageTimer32性能计数器,可以进行以下转换:varperformanceCounterTicks=timeSpan.Ticks*Stopwatch.Frequency/TimeSpan.TicksPerSecond;averageTimerCounter.IncrementBy(performanceCounterTicks);averageTimerCounterBase.Increment();这是一个旧线程,但我想我会插话。Microsoft的某个人告诉我,在使用性能计数器时我不应该使用TimeSpan、StopWatch或DateTime。相反,他建议将以下本机方法添加到我的项目中:递增计数器时,他建议这样做:以上是C#学习教程:HowtouseAverageTimer32andAverageBaseperformancecountersinSystem.Diagnostics.Stopwatch?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——publicvoidFoo(){varbeginTicks=0L;varendTicks=0L;NativeMethods.QueryPerformanceCounter(refbeginTicks);//做一些事情NativeMethods.QueryPerformanceCounter(refendTicks);this.Counter.IncrementBy(endTicks-beginTicks);这个.BaseCounter.Increment();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
