Timing Code With WatchMe, Part 1

It is often helpful to track the timing of sections of code. One way to accomplish this is to put messages directly into your code that displays the timings.

DISCLAIMER: this article is not about performance tuning of code, it is about simplifying incorporating timing during development.

Let’s take a look at a method that given an integer, returns the sum of all integers up to the passed integer, and has code to display timings.

If you call this method and pass 1,000,000 you will see output similar to the following:

SumUpTo started at  2019-12-22 20:51:02.420 UTC
SumUpTo – i = 0 0ms

SumUpTo – i = 1000000 6.9798ms
SumUpTo finished 6.9798ms

While helpful in determining where timing issues lie in the code, it has side effects:

  1. It adds several lines of code that have nothing to do with the behavior of the method – there are ten lines of code that do not relate to the calculation of the return value, which will impact timing. It may not be a significant impact, but there is an impact. The less we do, the less impact on timing we will experience.
  2. These extra lines of code are spread throughout the routine:
    • a start time is captured at the beginning
    • an elapsed time is calculated at several places
    • a periodic status message every 100,000 iterations of the loop
    • a summary message at the end, showing the elapsed time.
  3. Capturing elapsed time has accuracy and thread safety issues.  – there is a class in the .NET framework called Stopwatch that can help with this, we’ll see in a later part of this series.
  4. Removing the timing code can be tedious.

One approach I have used to make this cleaner and to address these issues is to simply wrap what I want to measure with a “using” statement that instantiates an instance of a class called WatchMe. Here is the same method, re-written using the WatchMe class:

Much cleaner, in fact if we take out the “if” statement surrounding the call to ShowMessage, the using takes care of all of the timings.

The WatchMe class takes care of the following:

  1. Takes advantage of the IDisposable interface to capture finish elapsed time, and logging the final elapsed time message.
  2. Uses the Stopwatch class to handle some of the issues with capturing elapsed time.
  3. Holds on to the title of what is being watched (e.g. SumUpTo)
  4. Captures the DateTime start variable used later to calculate the various elapsed times.
  5. Automatically displays the start and finished messages
  6. Simplifies the interim message to only the message: the title and elapsed times are added to the message automatically.

We’ll take a look at the WatchMe class in part 2 of this series.