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

前端 未结 3 1531
北恋
北恋 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();
    }
    

提交回复
热议问题