Tuesday, July 22, 2008

Using the Stopwatch Class for performing timing

images Previously I used to use the DateTime structure to determine elapsed time, especially for performance timing. DateTime is extremely easy to use but cannot be used to measure small spans of time.

With .NET 2.0, MS released the Stopwatch class. The main reason that this class is superior for performing really small measurements of elapsed time is that the Stopwatch class will use the hardware's high resolution performance counters if one is available. In addition the Stopwatch class counts the ticks that have elapsed, instead of the actual time. If a high resolution counter is not available - then the class will default to using the system's timer.


Here is how you can use it:

   1:  long ticks, totalTime;
2: long timeInMicroSeconds = 1000000L;
3: long timeInNanoSeconds = 1000000000L;
4: Stopwatch sw = new Stopwatch();
5: long freq = Stopwatch.Frequency;
6: sw.Start();
8: //////////////////////////////
9: //Code that needs to be timed
  10:              //////////////////////////////
12: sw.Stop();
13: ticks = sw.ElapsedTicks;
14: totalTime = timeInMicroSeconds * ticks/freq ; // use timeInNanoSeconds, if you want the elapsed time in Nano seconds

Read more at MSDN - Stopwatch Class (System.Diagnostics)

No comments: