I\'d like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs th
For highest resolution performance counters you can use the underlying win32 performance counters.
Add the following 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);
And call them using:
#region Query Performance Counter
///
/// Gets the current 'Ticks' on the performance counter
///
/// Long indicating the number of ticks on the performance counter
public static long QueryPerformanceCounter()
{
long perfcount;
QueryPerformanceCounter(out perfcount);
return perfcount;
}
#endregion
#region Query Performance Frequency
///
/// Gets the number of performance counter ticks that occur every second
///
/// The number of performance counter ticks that occur every second
public static long QueryPerformanceFrequency()
{
long freq;
QueryPerformanceFrequency(out freq);
return freq;
}
#endregion
Dump it all into a simple class and you're ready to go. Example (assuming a class name of 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()));