Вопрос

Я бы хотел выполнить базовое профилирование своего кода, но обнаружил, что DateTime.Теперь в 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 отлично подходит для профилирования.

Вот ссылка на блог таймера кода Vance Morrison если вы не хотите писать свои собственные функции измерения.

Для счетчиков производительности с самым высоким разрешением вы можете использовать базовые счетчики производительности win32.

Добавьте следующие подписки P / Invoke:

[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. Имя функции - QueryPerformanceCounter в kernel32.dll.

Синтаксис для импорта в 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