How to use AverageTimer32 and AverageBase performance counters with System.Diagnostics.Stopwatch?

前端 未结 3 1526
北恋
北恋 2021-02-02 10:15

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 w

相关标签:
3条回答
  • 2021-02-02 10:44

    This is an old thread, but I thought I'd chime in. I was told by someone from Microsoft that I shouldn't use TimeSpan, StopWatch, or DateTime when working with Performance Counters. Instead, he recommended adding the following native method to my project:

    internal static class NativeMethods
    {
        [DllImport("Kernel32.dll")]
        public static extern void QueryPerformanceCounter(ref long ticks); 
    }
    

    When incrementing a counter, he recommended doing so like this:

    public void Foo()
    {
        var beginTicks = 0L;
    
        var endTicks = 0L;
    
        NativeMethods.QueryPerformanceCounter(ref beginTicks);
    
        // Do stuff
    
        NativeMethods.QueryPerformanceCounter(ref endTicks);
    
        this.Counter.IncrementBy(endTicks - beginTicks);
        this.BaseCounter.Increment();
    }
    
    0 讨论(0)
  • 2021-02-02 10:48

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

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

    The documentation contains more information about this.

    0 讨论(0)
  • 2021-02-02 11:02

    Mark Seemann explained the confusing source of the problem but I would like to provide a little bit of additional information.

    If you want to set your AverageTimer32 performance counter from a TimeSpan and not a Stopwatch you can perform the following conversion:

    var performanceCounterTicks = timeSpan.Ticks*Stopwatch.Frequency/TimeSpan.TicksPerSecond;
    averageTimerCounter.IncrementBy(performanceCounterTicks);
    averageTimerCounterBase.Increment();
    
    0 讨论(0)
提交回复
热议问题