There are some really cool tools available to help you test and improve your programs in the.Net Framework.

One of the most simple is the Stopwatch class, situated in the System.Diagnostics namespace. As the name suggests it allows you to create a stopwatch object, and use it to time processes, operations or any other part of your program.

It might sound lke a waste of time to see how fast a small part of your program is, but making all of the smaller parts work better can have a great impact on the overall speed of the program so don't discount it as a method of improving your code.

The code to instantiate the stopwatch is just the same as most other objects, and to start and stop the stopwatch is also very straight forward:

Once you have used the stopwatch to time the running of your code, you can use the Elapsed property to access the time that has elapsed while the stopwatch has been running. It is displayed in the format of HH:MM:SS.0000000. (the first three 0’s represent milliseconds) The time stored in the stopwatch can also be accessed using the ElapsedMilliseconds property, which displays only the milliseconds that have elapsed.

The stopwatch can be read without being stopped, so you can access the Elapsed property and leave the stopwatch running, and then check the elapsed time again later to see the total time. If you want to use the intermittent timings later you can use a TimeSpan object to store the time and perform operations on it such as comparing two times.

Alternatively you can stop the stopwatch using Stop(), and then start the stopwatch again by calling Start(). This will cause the stopwatch to continue where it left off when it was stopped. You can clear the contents of  the stopwatch with the Reset() method, or to clear the stopwatch and start it again with only one method call you can call Restart(). This is preferable to using a new stopwatch as you then don’t need to create another stopwatch object.

Using the stopwatch has been really useful for assessing the speed of my programs, or algorithms. It has often made me refactor and optimise my code to make it run faster, and therefore make the whole application more snappy and responsive.

A prime example of this is in the Smallest Number Divisible by 1 - 20 where my original program took about 10 seconds to find the answer and I thought there must be a faster way. So using the timers to test various theories i came up with an altered algorithm that ran significantly faster than the original.