Geeks With Blogs
New Things I Learned

I’m finding that writing blogs actually take quite a bit of time; so I’m writing this fairly short blog in Live Writer, with the hope that I can be more productive since the tool will make it easier for me to blog.  So, we’ll see :).

I’ve used the Stopwatch class for as long as I can remember.  I don’t even remember whether I get to know the class from just browsing MSDN, or reading it from another blog, or just playing around typing stuff (and looking at what’s available through Intellisense).  Whenever I have some part of the code where I’d like to time, I’ve always used it.  So, it has been very natural for me to use.

It is surprising to me that every now and then, when I asked someone to time some new method that they create to replace an old method, they see it as a very time consuming process (pardon the pun).  Using the Stopwatch class is very, very easy!  You create it, start it, and stop it (optional), and then report the time that has elapsed.

Stopwatch sw = new Stopwatch();
sw.Start();

CallSomeMethodToTime();

sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());

Quite easy, really, as shown in the code snippet above, which shows the elapsed milliseconds for the method.  There’s even a way to create a Stopwatch that starts automatically – using the StartNew method.

Ah, but what if the time to measure is even smaller?  The snippet above uses the ElapsedMilliseconds property, which is nice, but what if the method takes less than a millisecond?  On a recent task I had to do, we have a method that is recursively called – the method execution itself is very fast (less than 1 millisecond), but higher up the stack the calling methods shows slower and slower time measurement.  It’s just a matter of the method gets called a LOT, so we would like to optimize the method, but we need a way to measure the method time which goes very fast.

This is where the ElapsedTicks property comes in.  The ElapsedTicks property gets the elapsed time, in ticks.  What’s good about this is that ticks have a high resolution – it is actually dependent on the computer itself.  If the computer (CPU actually) has a high resolution timer, it’ll use that.  As such, the resolution of this ‘Tick’ varies among computers.  This resolution is retrieved through the Frequency static property of the Stopwatch class – the value returned by Frequency denotes how many ticks are there in a second for that particular computer.

I have a fairly old Pentium 4 machine, and on my machine, Stopwatch.Frequency returns 3192160000 – so 1 second is denoted as 3,192,160,000 ticks, that’s a resolution of over 1 ns.  But, we’re not here to compare numbers – we’d like to know if we can measure things more accurately.  To show how many seconds have elapsed, we just need to divide ElapsedTicks with the Frequency value.

To ease the retrieval of these values, on my Helper project, I’ve added 2 extension methods, as follows:

public static class ExtensionMethods
{
   public static double ElapsedMilliseconds(this Stopwatch stopwatch)
   {
      if (stopwatch == null)
         throw new ArgumentException("Stopwatch passed cannot be null!");

      return 1000 * stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
   }

   public static double ElapsedMicroseconds(this Stopwatch stopwatch)
   {
      if (stopwatch == null)
         throw new ArgumentException("Stopwatch passed cannot be null!");

      return 1e6 * stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
   }
}

Having these extension methods, allow me to do the following code:

 

Stopwatch sw = new Stopwatch();
sw.Start();

SomeSlowMethod();

MessageBox.Show(sw.ElapsedMilliseconds().ToString("0.000 ms"));

sw.Reset();
sw.Start();

SomeFastMethod();

MessageBox.Show(sw.ElapsedMicroseconds().ToString("0.000 us"));

Looks almost like a property, but results in a method call instead.  And I can log / show time measurements to the microseconds.  For my current needs, this is pretty fast & accurate – on my P4 machine, setting a field took 0.8 microseconds, so even fast method calls will be in the tens or hundreds of microseconds.

I hope this helps others that would like to do some timings of their own.

Posted on Tuesday, July 14, 2009 12:08 PM .NET | Back to top


Comments on this post: Measure more accurately with Stopwatch

# re: Measure more accurately with Stopwatch
Requesting Gravatar...
Great codes. Thanks a lot for sharing this stuff. Keep on learning and sharing Mate.
Left by Eric Graham The Conversion Docto on Apr 06, 2011 3:47 AM

# re: Measure more accurately with Stopwatch
Requesting Gravatar...
This helped me alot! Have been trying to make an "gameloop timer" for 2 days but it always returned 0. Thanks mate
Left by Asken on Aug 19, 2013 9:53 AM

Your comment:
 (will show your gravatar)


Copyright © Muljadi Budiman | Powered by: GeeksWithBlogs.net