当我执行以下程序并查看性能计数器时,结果对我来说没有意义。当我期望〜0.1或〜100时,平均值为零,最小/最大值为〜0.4。
我怎么了
代码
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
最佳答案
System.Diagnostics API包含一个非常细微的困惑来源:System.Diagnostics“滴答”与DateTime或TimeSpan“滴答”不同!
如果使用StopWatch.ElapsedTicks而不是StopWatch.Elapsed.Ticks,它应该可以工作。
documentation包含有关此信息的更多信息。