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

Monday, October 09, 2006 8:23:20 PM (Central European Standard Time, UTC+01:00)
Thanks dude! That was very helpful
Tuesday, November 24, 2009 7:39:42 AM (Central European Standard Time, UTC+01:00)
Good afternoon. He who is not very strong in memory should not meddle with lying.
I am from Tonga and also now'm speaking English, give true I wrote the following sentence: "Mortgage note, florida statues in process to default a snatched, used or built acceptable value."

Waiting for a reply :), Hamlin.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview