.NET中的高分辨率计时器

时间:2008-10-02 15:30:14

标签: .net profiling timer

我想对我的代码进行一些基本的分析,但发现C#中的DateTime.Now只有大约16 ms的分辨率。必须有更好的时间来保存我尚未找到的构造。

4 个答案:

答案 0 :(得分:55)

以下是对操作进行计时的示例代码:

Dim sw As New Stopwatch()
sw.Start()
//Insert Code To Time
sw.Stop()
Dim ms As Long = sw.ElapsedMilliseconds
Console.WriteLine("Total Seconds Elapsed: " & ms / 1000)

编辑:

整洁的事情是它也可以恢复。

Stopwatch sw = new Stopwatch();
foreach(MyStuff stuff in _listOfMyStuff)
{
    sw.Start();
    stuff.DoCoolCalculation();
    sw.Stop();
}
Console.WriteLine("Total calculation time: {0}", sw.Elapsed);

System.Diagnostics.Stopwatch类将使用高分辨率计数器(如果系统上有可用的计数器)。

答案 1 :(得分:20)

System.Diagnostics.StopWatch类非常适合分析。

如果您不想编写自己的测量函数,请输入Vance Morrison's Code Timer Blog

答案 2 :(得分:7)

对于最高分辨率的性能计数器,您可以使用底层的win32性能计数器。

添加以下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);

并使用以下方式调用它们:

#region Query Performance Counter
/// <summary>
/// Gets the current 'Ticks' on the performance counter
/// </summary>
/// <returns>Long indicating the number of ticks on the performance counter</returns>
public static long QueryPerformanceCounter()
{
    long perfcount;
    QueryPerformanceCounter(out perfcount);
    return perfcount;
}
#endregion

#region Query Performance Frequency
/// <summary>
/// Gets the number of performance counter ticks that occur every second
/// </summary>
/// <returns>The number of performance counter ticks that occur every second</returns>
public static long QueryPerformanceFrequency()
{
    long freq;
    QueryPerformanceFrequency(out freq);
    return freq;
}
#endregion

将它全部转移到一个简单的课程中,你准备好了。示例(假设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()));

答案 3 :(得分:1)

您可以在Windows中调用高分辨率性能计数器。函数名是kernel32.dll中的QueryPerformanceCounter。

导入C#的语法:

[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

Windows调用语法:

BOOL QueryPerformanceCounter(      
    LARGE_INTEGER *lpPerformanceCount
);

QueryPerformanceCounter @ MSDN

相关问题