Saturday, May 30, 2009

Benchmark/performance timers

// Benchmark/performance timers (See Example tab for usage)

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; }
}
}

No comments:

Post a Comment