2008-10-02 79 views
29

我想对我的代码做一些基本的分析,但发现C#中的DateTime.Now只有约16毫秒的分辨率。必须有更好的时间保持我还没有找到的构造。.NET高分辨率计时器

回答

48

这里是一个代码示例位时的操作:

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类将使用高分辨率计数器,如果一个是在系统上可用。

18

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

如果您不想编写自己的测量功能,可以链接到Vance Morrison's Code Timer Blog

+0

是的,那一个计数高分辨率时钟(如果存在)的滴答声......正是我所需要的。 – 2008-10-02 15:32:59

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

6

对于最高分辨率的性能计数器,您可以使用基础的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())); 
+9

从.NET 2.0开始,Stopwatch类会为你做这件事。 – 2008-10-02 15:54:32