I normally use Stopwatch, but I have also used p/invoke to kernel32.dll:
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
I have two methods called Start() and Stop():
public void Start()
{
Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
To query the duration between calls to Start() and Stop():
public double Duration
{
get
{
return (double)(stopTime - startTime)*1000 / (double)freq;
}
}
Note that freq
is determined in the constructor:
public PerformanceTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
// not supported
throw new Win32Exception();
}
}
For my needs, I have not noticed much of a difference, although I suggest you try both to see what suits you.
Edit: I was able to locate the original code from MSDN. It appears there are some improvements made since .Net 1.1. The take-home message is that Microsoft claims that this method provides nanosecond accuracy.