2008-10-02 81 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