Debug Stopwatch and Performance monitoring

Tuesday, June 12, 2018

By: Chris Dunn

If you're into performance analysis you will want to know about .net's Stopwatch class in the System.Diagnostics namespace.  It's great for monitoring the execution time of an operation and identifying performance black holes in your code.  It's also more precise and performant than using repeated DateTime.Now calls (which we're all guilty of doing).  Understand that Stopwatch is not your only option and in certain cases PerformanceCounters may be a better solution. Here's the basic code to get you started.

           //create stopwatch
            Stopwatch sw = new Stopwatch();

            //start stopwatch
            sw.Start();

            //pause
            Thread.Sleep(5000);

            //stop stopwatch
            sw.Stop();

            //report results in ms
            Debug.WriteLine("Execution completed in {0} ms.", sw.Elapsed.TotalMilliseconds);

There is an impact on performance when using the Stopwatch.  So, a lot of stopwatch calls can degrade the performance of your application in production.  You could wrap all your Stopwatch code in #if DEBUG calls, but that gets ugly to maintain.

NOTE: While most Debug methods have the [Conditional("DEBUG")] attribute , the stopwatch does not. So even though you're not recording time, the calculation of elapsed still has performance impact.

So instead I use a wrapper for the Stopwatch class that utilizes the Conditional Attribute to ignore the calls to the methods when compiled into a release build.

/// 
    /// Wrapper for stop watch for use only in debug mode,
    /// and removing from compiled release.
    /// 
    public class DStopWatch
    {
       

        /// 
        /// Diagnostics stopwatch instance used internal to class.
        /// 
        private System.Diagnostics.Stopwatch _stopWatch;
        private System.Diagnostics.Stopwatch StopWatch {
            get {
                Debug.WriteLine("Init Stopwatch");
                if (_stopWatch == null)
                    _stopWatch = new System.Diagnostics.Stopwatch();
                
                return _stopWatch;
            }
        }
        
        /// 
        /// Start the Debug Stopwatch
        /// 
        [Conditional("DEBUG")]
        public void Start()
        {
            Debug.WriteLine("Start Stopwatch");
            StopWatch.Start();
        }

        /// 
        /// Stop the Debug Stopwatch
        /// 
        [Conditional("DEBUG")]
        public void Stop()
        {
            Debug.WriteLine("Stop Stopwatch");
            StopWatch.Stop();
            Elapsed = _stopWatch.Elapsed;
        }

        /// 
        /// Return the elapsed time as a timespan
        /// 
        public TimeSpan Elapsed { get; set; }
    }

Tags: c# debug performance

Copyright 2019 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.