Tuesday 15 December 2009

A c# timer stopwatch class to help analyse lengthy program execution

I have recently been developing a piece of software that uses the old Microsoft COM Interop technology to walk through a Sharepoint 2001 folder structure. I found that this was working pretty slowly, but by the time I came around to do anything about it the code had got fairly complicated and it wasn't clear where the bottleneck was occuring.

To help understand the problem I created this simple static timer class:
class Timer
    {
        static public DateTime timeStart;
        static public DateTime timeEnd;
        static public bool debugTimer = true;  //Switch to false to turn off timing messages
 
        public  Timer()
        {
        }
 
        static public void TimerStart(string msg)
        {
            if (! debugTimer) return;
            timeStart = DateTime.Now;
            Console.WriteLine("TIMER: " + msg + " BEGUN: " + timeStart.ToString(), true);
        }
 
        static public void TimerEnd()
        {
            if (!debugTimer) return;
            timeEnd = DateTime.Now;
            TimeSpan totalTime = new TimeSpan();
            totalTime = timeEnd.Subtract(timeStart);
 
            Console.WriteLine("TIMER END: " + timeEnd.ToString() + " Total time: " + totalTime.Milliseconds, true);
        }
    }

In order to use this in your code, simply copy the class and put the following lines around whatever process you wish to monitor:
Timer.TimerStart("Beginning timer");
    //...
    //do lenghtly process
    //...
    Timer.TimerEnd();

This will give a nice message, with the time elapsed in milliseconds.