My Thoughts & Views

C# Code for measuring application performance

Posted on: March 24, 2008

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

Advertisements

2 Responses to "C# Code for measuring application performance"

You write very well.

You write very well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: