Usage:
NormalTimer timer1 = new NormalTimer();
timer1.Start();
for (int i = 0; i < 1000 * 1000 * 1000; i++) ;
timer1.Stop();
Console.WriteLine("Duration: {0} seconds", timer1.durationS);
PrecisionTimer timer2 = new PrecisionTimer();
timer2.Start();
for (int i = 0; i < 1000 * 1000 * 1000; i++) ;
timer2.Stop();
Console.WriteLine("Duration: {0} seconds", timer2.durationS);
internal class UnmanagedApi
{
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceFrequency(
out long lpFrequency);
}
public class PrecisionTimer
{
private long startTick;
private long stopTick;
private long tickFrequency;
public PrecisionTimer()
{
UnmanagedApi.QueryPerformanceFrequency(out tickFrequency);
}
internal class UnmanagedApi
{
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
internal static extern bool QueryPerformanceFrequency(
out long lpFrequency);
}
public void Start()
{
Thread.Sleep(0); //execute waiting threads first, then continue
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
UnmanagedApi.QueryPerformanceCounter(out startTick);
}
public void Stop()
{
UnmanagedApi.QueryPerformanceCounter(out stopTick);
}
public static long Tick()
{
long retVal;
UnmanagedApi.QueryPerformanceCounter(out retVal);
return retVal;
}
private long ticks
{
get
{
if (startTick > stopTick)
{
startTick = stopTick = 0;
return 0;
}
else
{
return (stopTick - startTick);
}
}
}
public void WriteLine()
{
Console.WriteLine("{0} ms", durationMs);
}
public double durationS
{
get { return (double) ticks/tickFrequency; }
}
public double durationMs
{
get { return durationS*1000; }
}
}
public class NormalTimer
{
private long startTick;
private long stopTick;
public void Start()
{
Thread.Sleep(0); //execute waiting threads first, then continue
startTick = Environment.TickCount;
}
public void Stop()
{
stopTick = Environment.TickCount;
}
private long ticks
{
get
{
if (startTick > stopTick)
{
startTick = stopTick = 0;
return 0;
}
else
{
return (stopTick - startTick);
}
}
}
public long durationMs
{
get { return ticks; }
}
public double durationS
{
get { return (double) ticks/1000; }
}
}