Execution Timer For Helping With Efficiency

// December 11th, 2009 // Useful Code

This class is useful when checking times which functions take to execute. Simply instantiate this class and when you are done timing call the StopTimer function and then you can display how long something too to execute. I use this class all over the place when I have three different ideas but am not sure which one will execute faster.

//Class


    class ExecutionTimer
    {
        //PRIVATE VARIABLES FOR HOLDING THE TIME INFORMATION
        private long startTime;
        private long stopTime;

        //DEFAULT CONSTRUCTOR JUST CALLS THE START TIMER
        public ExecutionTimer()
        {
            StartTimer();
        }

        /// <summary>
        /// MARK THE START TIME FOR CALCULATIONS
        /// </summary>
        public void StartTimer()
        {
            startTime = DateTime.Now.Ticks;
        }

        /// <summary>
        /// MARK THE STOP TIME FOR CALCULATIONS
        /// </summary>
        public void StopTimer()
        {
            stopTime = DateTime.Now.Ticks;
        }

        /// <summary>
        /// DEFAULT OVERRIDE OF TOSTRING TO FORMAT THE OUTPUT AS A VALID TIME STRING
        /// </summary>
        /// <returns>FORMATTED TIME STRING IN FORMAT OF HH:MM:SS.MILISECONDS</returns>
        public override string ToString()
        {
            return ToString(1);
        }

        /// <summary>
        /// OUTPUT THE STRING USING AN AVERAGE COUNTER INCASE THE USER RAN THE TRACKING MORE THEN ONCE WE NEED TO AVG THE TIME
        /// </summary>
        /// <param name="avg">DIVISOR</param>
        /// <returns>FORMATTED TIME STRING IN FORMAT OF HH:MM:SS.MILISECONDS AVERAGED OVER X ATTEMPTS</returns>
        public string ToString(long avg)
        {
            //VERIFY THAT AVG IS A VALID VALUE
            if (avg == 0)
                throw new ArgumentException("Avg can not be 0", "avg");

            //RETURN THE FORMATTED STRING FROM THE NEW DATE
            return string.Format("{0:HH:mm:ss.ff}", new DateTime((stopTime - startTime) / avg));
        }
    }

//Usage


    class Program
    {
        static void Main(string[] args)
        {
            ExecutionTimer tmpTimer = new ExecutionTimer();
            System.Threading.Thread.Sleep(5500);
            tmpTimer.StopTimer();
        }
    }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt