如何使用AverageTimer32和AverageBase性能计数器与System.Diagnostics.Stopwatch?如何使用、计数器、性能、Stopwatch

由网友(女神,快到我怀里来)分享简介:当我执行下面的程序,并期待在性能计数器的结果没有任何意义了我。平均值为零,最小/最大值〜0.4时,我会想到〜0.1〜100。When I execute the following program and look at the performance counter the results don't make s...

当我执行下面的程序,并期待在性能计数器的结果没有任何意义了我。平均值为零,最小/最大值〜0.4时,我会想到〜0.1〜100。

When I execute the following program and look at the performance counter the results don't make sense to me. The average value is zero and the min/max values are ~0.4 when I would expect ~0.1 or ~100.

什么是我的问题吗?

code

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

推荐答案

在System.Diagnostics程序API包含了很大的混乱pretty的微妙来源:System.Diagnostics程序蜱是不一样的日期时间或时间跨度蜱'!

The System.Diagnostics API contains a pretty subtle source of great confusion: System.Diagnostics 'ticks' are not the same as DateTime or TimeSpan 'ticks'!

如果您使用StopWatch.ElapsedTicks而不是StopWatch.Elapsed.Ticks,它应该工作。

If you use StopWatch.ElapsedTicks instead of StopWatch.Elapsed.Ticks, it should work.

的documentation包含更多相关信息。

阅读全文

相关推荐

最新文章