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

A simple way to use a Stopwatch

By , 25 Dec 2011
 
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
Member
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
 

"Omit needless local variables." -- Strunk... had he taught programming
 
"DON'T BE LIBERAL IN WHAT YOU ACCEPT!"
 
"Software Engineers don't have Trophy Wives; they have Presentation Layers."
 
"We learn more from our mistakes than we do from getting it right the first time."
 
"I'm an old dog and I like old tricks."
 
"Sometimes the envelope pushes back and sometimes you get a really nasty paper cut."
 
"A method shall have one and only one return statement."
 
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."
 
"Today's heresy is tomorrow's dogma."
or
"Today's dogma is yesterday's heresy."

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionIsRunning?membervxrex26 Dec '11 - 4:09 
AnswerRe: IsRunning?memberPIEBALDconsult6 Dec '11 - 12:57 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 25 Dec 2011
Article Copyright 2011 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid