Monday, March 24, 2008

C# Code for measuring application performance

The DateTime class is not very exact and only can measure in milliseconds. When doing performance measuring on an application you most certainly need to be able to measure with smaller time units than that. High-resolution timers are supported in the Win32 API so following code wraps it up in a simple class:

public class PerformanceTimer
{
[DllImport("Kernel32.dll")]
public static extern void QueryPerformanceCounter(ref long ticks);

long startTime = 0;
long stopTime = 0;

public void Start()
{
QueryPerformanceCounter(ref startTime);
}

public void Stop()
{
QueryPerformanceCounter(ref stopTime);
}

public long Time
{
get
{
return stopTime - startTime;
}
}
}

I’m sure the code is easy to understand. Here is the sample code to show how to use it.

PerformanceTimer perfoTimer = new PerformanceTimer();
perfTimer.Start();

// Do something

perfTimer.Stop();
System.Diagnostics.Trace.WriteLine(perfoTimer.Time);

1 comment:

Anonymous said...

You write very well.