High resolution timer in .NET

后端 未结 4 1973
一整个雨季
一整个雨季 2020-12-09 14:57

I\'d like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs th

4条回答
  •  一个人的身影
    2020-12-09 15:41

    For highest resolution performance counters you can use the underlying win32 performance counters.

    Add the following P/Invoke sigs:

    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    public static extern bool QueryPerformanceCounter(out long perfcount);
    
    [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
    public static extern bool QueryPerformanceFrequency(out long freq);
    

    And call them using:

    #region Query Performance Counter
    /// 
    /// Gets the current 'Ticks' on the performance counter
    /// 
    /// Long indicating the number of ticks on the performance counter
    public static long QueryPerformanceCounter()
    {
        long perfcount;
        QueryPerformanceCounter(out perfcount);
        return perfcount;
    }
    #endregion
    
    #region Query Performance Frequency
    /// 
    /// Gets the number of performance counter ticks that occur every second
    /// 
    /// The number of performance counter ticks that occur every second
    public static long QueryPerformanceFrequency()
    {
        long freq;
        QueryPerformanceFrequency(out freq);
        return freq;
    }
    #endregion
    

    Dump it all into a simple class and you're ready to go. Example (assuming a class name of PerformanceCounters):

    long startCount = PerformanceCounter.QueryPerformanceCounter();
    // DoStuff();
    long stopCount = PerformanceCounter.QueryPerformanceCounter();
    long elapsedCount = stopCount - startCount;
    double elapsedSeconds = (double)elapsedCount / PerformanceCounter.QueryPerformanceFrequency();
    MessageBox.Show(String.Format("Took {0} Seconds", Math.Round(elapsedSeconds, 6).ToString()));
    

提交回复
热议问题