مؤقت عالي الدقة في .NET
سؤال
أرغب في إجراء بعض التوصيفات الأساسية للكود الخاص بي، لكنني وجدت أن دقة DateTime.Now في C# تبلغ حوالي 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 رائعة للتوصيف.
هنا رابط ل مدونة مؤقت الكود الخاصة بفانس موريسون إذا كنت لا ترغب في كتابة وظائف القياس الخاصة بك.
لأعلى عدادات الأداء قرار يمكنك استخدام عدادات الأداء Win32 والأساسية.
وإضافة P التالية / استدعاء سغس:
[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()));
ويمكن استدعاء وصولا الى عداد الأداء ذات الدقة العالية في ويندوز. اسم الدالة QueryPerformanceCounter في Kernel32.dll.
وبناء الجملة للاستيراد إلى C #:
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
وبناء الجملة من أجل الدعوة ويندوز:
BOOL QueryPerformanceCounter(
LARGE_INTEGER *lpPerformanceCount
);