Pregunta

Me gustaría hacer un perfil básico de mi código, pero descubrí que DateTime. Ahora en C # solo tiene una resolución de aproximadamente 16 ms. Debe haber un mejor tiempo para mantener las construcciones que aún no he encontrado.

¿Fue útil?

Solución

Aquí hay una muestra de código para cronometrar una operación:

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)

EDITAR:

Y lo mejor de todo es que también se puede reanudar.

Stopwatch sw = new Stopwatch();
foreach(MyStuff stuff in _listOfMyStuff)
{
    sw.Start();
    stuff.DoCoolCalculation();
    sw.Stop();
}
Console.WriteLine("Total calculation time: {0}", sw.Elapsed);

La clase System.Diagnostics.Stopwatch será use un contador de alta resolución si hay uno disponible en su sistema.

Otros consejos

La clase System.Diagnostics.StopWatch es impresionante para crear perfiles.

Aquí hay un enlace a Blog del temporizador de códigos de Vance Morrison si no desea escribir sus propias funciones de medición.

Para los contadores de rendimiento de resolución más alta, puede usar los contadores de rendimiento win32 subyacentes.

Agregue las siguientes firmas 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);

Y llámalos usando:

#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

Voltee todo en una clase simple y estará listo para comenzar. Ejemplo (asumiendo un nombre de clase de 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()));

Puede llamar al contador de rendimiento de alta resolución en Windows. El nombre de la función es QueryPerformanceCounter en kernel32.dll.

Sintaxis para importar en C #:

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

Sintaxis para llamada de Windows:

BOOL QueryPerformanceCounter(      
    LARGE_INTEGER *lpPerformanceCount
);

QueryPerformanceCounter @ MSDN

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top