Click here to Skip to main content
15,881,380 members
Articles / Stopwatch
Tip/Trick

A simple way to use a Stopwatch

Rate me:
Please Sign up or sign in to vote.
1.67/5 (2 votes)
25 Dec 2011CPOL 25.5K   4   4
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)


Written By
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, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"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

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

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

Comments and Discussions

 
GeneralReason for my vote of 3 Looks OK, but stopwatch is just a wr... Pin
ChunkyStool3-Jan-12 11:57
ChunkyStool3-Jan-12 11:57 
Reason for my vote of 3
Looks OK, but stopwatch is just a wrapper for a couple of timestamps. That's why StopWatch isn't disposable -- it contains value types. I would have just created a custom stopwatch class that included the start counter.
As far as the collection goes, custom collections are easy. (Derive from Collection<T>).
Making the class disposable isn't necessary.
General<a href="http://www.codeproject.com/script/comments/View.asp... Pin
thatraja28-Nov-11 21:52
professionalthatraja28-Nov-11 21:52 
QuestionIsRunning? Pin
vxrex26-Dec-11 4:09
vxrex26-Dec-11 4:09 
AnswerRe: IsRunning? Pin
PIEBALDconsult6-Dec-11 12:57
mvePIEBALDconsult6-Dec-11 12:57 

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

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