Monday, October 09, 2006

Since the version 1.1 of the .NET framework I have been mesuring the performance of my code using the same simple pattern. This basically was something like this:

DateTime begin = DateTime.Now;
DoSomething();
DateTime end = DateTime.Now;
TimeSpan duration = end - begin;

For long running tasks it was good enough, but if a task was very short, often the difference between the begin and end was 0.

Such as the following code:

private void DoSomething()
{
   
int a = 1;
   
for (long i = 0; i < 100; i++)
   {
      a = a + a - 1;
   }
}

Which's duration allways equals to 0 on my, not so fast, machine.

Of course this is a known "feature" of the DateTime now in that it is far from perfect for messuring short periods of time.

So how do you messure the performance of your code without calling some unmanaged functions? Is it at all possible? In 1.1 I do not think so, but fortunately .NET 2.0 comes with a new class called Stopwatch.

The Stopwatch type is defined in the System.Diagnostics namespace and "Provides a set of methods and properties that you can use to accurately measure elapsed time" (MSDN). The code above used the imperfect DateTime.Now can now be written as follows:

Stopwatch sw = new Stopwatch();
sw.Start();
DoSomething();
sw.Stop();
TimeSpan duration = sw.Elapsed;

Beside the fact that the duration will be much more accurate, the Stopwatch offers you a cleaner API to messure your time.

kick it on DotNetKicks.com