Need a high resolution timer
I like to profile my code regularly to see if any changes I make during development affect performance. In .Net 1.1 there is a distinct lack of a high resolution timer object. Here's one you can use:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace myNamespace
{
[DebuggerStepThrough()]
public class HiPerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(
ref long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(
ref long lpFrequency);
private long startTime, stopTime;
private long freq;
// Constructor
public HiPerfTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(ref freq) == false)
{
// high-performance counter not supported
throw new Win32Exception();
}
}
// Start the timer
public void Start()
{
// lets the waiting threads do their work
Thread.Sleep(0);
QueryPerformanceCounter(ref startTime);
}
// Stop the timer
public void Stop()
{
QueryPerformanceCounter(ref stopTime);
}
// Returns the duration of the timer
public double Duration
{
get
{
return (double)(stopTime - startTime) / (double) freq;
}
}
}
}
Call like this:
HiPerfTimer myTimer = new HiPerfTimer();
myTimer.Start();
//Do some stuff that needs timing here...
myTimer.Stop();
MessageBox.Show(myTimer.Duration.ToString())