Click here to Skip to main content
Click here to Skip to main content

A simple way to use a Stopwatch

, 25 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Making Stopwatches easier to insert (and remove) when looking for bottlenecks
My tool of choice for finding out how long a piece of code executes is the System.Diagnostics.Stopwatch. In many cases (mostly utility console applications), I can add one, use it, and report its Elapsed time very easily. But last week, I needed to investigate some convoluted code that I didn't write. I needed to time several different areas without affecting the structure of the classes and then remove my code when I was done.
 
I also wanted a count of how many times the Stopwatch was started, so I wrapped a Stopwatch in a very simple class:
 
namespace PIEBALD.Types
{
  public class Stopwatch : System.IDisposable
  {
    private readonly System.Diagnostics.Stopwatch stopwatch ;
 
    public Stopwatch
    (
    )
    {
      this.CountOfStarts = 0 ;
      this.stopwatch = new System.Diagnostics.Stopwatch() ;
      return ;
    }
 
    public virtual ulong CountOfStarts { get ; private set ; }
 
    public virtual System.TimeSpan
    Elapsed
    {
      get
      {
        return ( this.stopwatch.Elapsed ) ;
      }
    } 
 
    public virtual void
    Start
    (
    )
    {
      if ( !this.IsRunning )
      {
        this.CountOfStarts++ ;
        this.stopwatch.Start() ;
      }
      return ;
    }
 
    public virtual void
    Stop
    (
    )
    {
      this.stopwatch.Stop() ;
      return ;
    }
 
    public virtual void
    Dispose
    (
    )
    {
      this.Stop() ;
      return ;
    }
 
    public override string
    ToString
    (
    )
    {
      return ( System.String.Format
      (
        "{0} elapsed during {1} period{2}"
      ,
        this.Elapsed
      ,
        this.CountOfStarts
      ,
        this.CountOfStarts==1?"":"s"
      ) ) ;
    }
  }
}
 
I pass through a few other methods as well, but they're less important. The important bit is the Start that increments the count, and the Dispose that stops the Stopwatch.
 
Then I wrapped a Dictionary in a static class:
 
namespace PIEBALD.Types
{
  public static class StopwatchOmatic
  {
    public static System.Collections.Generic.Dictionary<string,PIEBALD.Types.Stopwatch> Items { get ; private set ; }
 
    static StopwatchOmatic
    (
    )
    {
      Items = new System.Collections.Generic.Dictionary<string,PIEBALD.Types.Stopwatch>() ;
      return ;
    }
 
    public static PIEBALD.Types.Stopwatch
 
    Stopwatch
    (
      string Name
    )
    {
      PIEBALD.Types.Stopwatch result ;
      if ( !Items.TryGetValue ( Name , out result ) )
      {
        Items [ Name ] = result = new PIEBALD.Types.Stopwatch() ;
      }
      return ( result ) ;
    }
 
    public static PIEBALD.Types.Stopwatch
    Start
    (
      string Name
    )
    {
      PIEBALD.Types.Stopwatch result = Stopwatch ( Name ) ;
      result.Start() ;
      return ( result ) ;
    }
 
    public static System.Collections.Generic.IEnumerable<string>
    Results
    {
      get
      {
        foreach
        (
System.Collections.Generic.KeyValuePair<string,PIEBALD.Types.Stopwatch> p
        in
          Items
        )
        {
          yield return ( System.String.Format
          (
            "Stopwatch {0} indicates {1}"
          ,
            p.Key
          ,
            p.Value
          ) ) ;
        }
        yield break ;
      }
    }
  }
}
 
In this way, it's quite simple to wrap some code I want to time like so:
 
using ( PIEBALD.Types.Stopwatch sw = PIEBALD.Types.StopwatchOmatic.Start ( "Loop 1" ) )
{
  /* Some suspicious code */
  /* You may also use sw.Stop() in here if your needs require it */
}
 
Then report the Elapsed times of the various Stopwatches like this:
 
foreach ( string s in PIEBALD.Types.StopwatchOmatic.Results )
{
  System.Console.WriteLine ( s ) ;
}
 
So adding and removing Stopwatches, ensuring that they Stop in case of an Exception, then reporting on them has become much simpler.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PIEBALDconsult
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology
 
Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.
 
OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB
 
---------------
 
"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]
 
"Typing is no substitute for thinking." -- R.W. Hamming
 
"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup
 
ZagNut’s Law: Arrogance is inversely proportional to ability.
 
"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon
 
"linq'ish" sounds like "inept" in German -- Andreas Gieriet
 
"Things would be different if I ran the zoo." -- Dr. Seuss
 
"Wrong is evil, and it must be defeated." – Jeff Ello
 
"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw
 
“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Omit needless local variables." -- Strunk... had he taught programming
 

 
"We learn more from our mistakes than we do from getting it right the first time."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."

Comments and Discussions

 
GeneralReason for my vote of 3 Looks OK, but stopwatch is just a wr... PinmemberChunkyStool3-Jan-12 11:57 
General<a href="http://www.codeproject.com/script/comments/View.asp... Pinmvpthatraja28-Nov-11 21:52 
QuestionIsRunning? Pinmembervxrex26-Dec-11 4:09 
Missing a property?
AnswerRe: IsRunning? PinmemberPIEBALDconsult6-Dec-11 12:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 25 Dec 2011
Article Copyright 2011 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid