Sunday, 9 June 2013

Using Stopwatch to measure execution speed in C#

 There are a number of ways to measure execution time in C# (including using DateTime class to get two "current" times, one at the start of the target code block and another at the end, and subtracting the former from the latter), and Stopwatch class in System.Diagnostics namespace is a fairly convenient one.

 You can initialise a Stopwatch instance and use it in the same way as the physical stopwatch; Start, Stop, and Reset it.

1. Instantiating 

 Make sure you include System.Diagnostics namespace by writing;
using System.Diagnostics;
  at the top of the file. This will then allow you to use Stopwatch class;
Stopwatch watch = new Stopwatch();

 2. Start, Stop, Reset

 Start the stopwatch at the beginning of the code block you want to measure execution time for, by invoking Start() method on "watch" object. This should come before you enter the code block. 
watch.Start();
 Then at the end of the code block, invoke Stop() method to stop the stopwatch.
watch.Stop();
 The stopwatch has now stopped running and has an elapsed time stored within the "watch" instance as its property. Stopwatch class provides three basic formats; firstly, a TimeSpan value which keeps values formatted in hours, minutes, seconds, etc.. Secondly, time in milliseconds as a long value. And thirdly, elapsed 'tick's as a long value.
 The first format would be useful if the expected execution time is more than a few seconds (or maybe few hours long) and you only need to visually see the result, or need to get each unit (year, hour...) separately.
 The second ElalsedMilliseconds format, on the other hand, would be useful if you are expecting very short execution time or need to deal with the result value in milliseconds as a whole number (for example, you may only need accuracy up to a millisecond and do not need any trailing values).

 You can reset or restart the timer in similar ways;
watch.Reset(); 
watch.Restart(); 
 Resetting the stopwatch would set the elapsed values to 0 and stop it too, whereas restarting would only set the values to 0 and continue running (if not started yet, it will start the watch).

3. Printing out the values

 These properties can be printed out via Console.WriteLine(). 

4. Alternative way of creating StopWatch instance

You can also create and start a StopWatch instance directly from static method "StopWatch.StartNew()".
Stopwatch watch = Stopwatch.StartNew();
 This simply replaces lines 11 and 12 of the example code above.



No comments:

Post a Comment