Using the Stopwatch Class to Log Time

The Stopwatch class is a really useful way to measure elapsed time in C#. It can be used to keep track of average request times, to send messages to the user based on how long an action might take, or to benchmark your code. Often the DateTime method (which is used to track the current date/time) is used to measure the passing of time, but using DateTime is hardy as efficient as using the Stopwatch class, which will yield more accurate results from more concise code.

To use it, you have to create a new instance of Stopwatch() and tell it when to stop and start.

Stopwatch timer = new Stopwatch();
// insert some code to execute here
Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", stopwatch.Elapsed);

Because there’s no code to execute in this example, the time elapsed will have been 0 hours/mins/seconds. As you can see, the code above is much more concise than the common practice of setting two DateTime variables and subtracting the difference between them to calculate how much time has elapsed. Stopwatch also has many different properties you should learn about if you plan on taking advantage of the class, including properties that allow you to reset the stopwatch, check to see if it’s still running, or see how many ‘ticks’ have elapsed (this can then be converted into seconds). Learn more about the stopwatch properties here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download