質問

コードの基本的なプロファイリングを行いたいのですが、C#のDateTime.Nowの解像度は約16ミリ秒に過ぎないことがわかりました。私がまだ見つけていないコンストラクトを保持するより良い時間があるはずです。

役に立ちましたか?

解決

操作の時間を計るためのサンプルコードを次に示します。

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 クラスは、システムで使用可能な場合は、高解像度のカウンターを使用してください。

他のヒント

System.Diagnostics.StopWatchクラスはプロファイリングに最適です。

Vance Morrisonのコードタイマーブログへのリンク a>独自の測定機能を作成したくない場合。

最高解像度のパフォーマンスカウンターには、基礎となるwin32パフォーマンスカウンターを使用できます。

次のP / Invoke sigを追加します。

[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()));

Windowsの高解像度パフォーマンスカウンターを呼び出すことができます。関数名はkernel32.dllのQueryPerformanceCounterです。

C#にインポートするための構文:

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

Windows呼び出しの構文:

BOOL QueryPerformanceCounter(      
    LARGE_INTEGER *lpPerformanceCount
);

QueryPerformanceCounter @ MSDN

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top