Home About

January 7th, 2009

Timing C# function performance with the Stopwatch class - 1

Timing C# function execution time with a stopwatch
Occasionally you need to time the performance of a C# function to see if its as fast, or as slow, as you think it is. You could of course run your code through a profiler. But in situations that that would be overkill there exists a quick solution. Originally I looked at the standard DateTime class, but NET 2.0 introduced the  Stopwatch class which is much more suitable. In this post I look at how you can measure your functions performance down to the last fraction of a millisecond.

How not to measure your C# functions execution time

The DateTime.Now function returns the current time on your computer, down to the millisecond. A simple approach to measuring the time of a function would thus be:

DateTime Start = DateTime.Now;

for (int Lp = 0; Lp < 100; Lp++)
Console.WriteLine("Hello World!");

TimeSpan Elapsed = DateTime.Now - Start;
Console.WriteLine("Time Elapsed: {0} ms",Elapsed.Milliseconds);

The problem is that according to MSDN the resolution of the DateTime.Now function is 10+ milliseconds, and we need to call it twice! So that would introduce a 20+ ms swing in your runtime measurement. As our function calls are often likely to be a lot quicker to return than this 20ms window this isn’t good enough.

Another approach would be to use the system tickcount as kept by the Environment.TickCount variable, which is also kept in milliseconds. This keeps the number of milliseconds since the computer was started. Unfortunately it is kept in a signed int, so that every 49 days (how often do you reset your computer?) it is actually counting backwards. We can compensate for this by just taking off the most siginificant bit.

int Start = Environment.TickCount &amp;amp;amp; Int32.MaxValue;

for (int Lp = 0; Lp < 100; Lp++)
Console.WriteLine("Hello World!");

int Elapsed = (Environment.TickCount &amp;amp;amp; Int32.MaxValue) - Start;
Console.WriteLine("Time Elapsed: {0} ms",Elapsed);

Using the Stopwatch class

The .NET 2.0 libraries introduced the Stopwatch class in System.Diagnostics which is much better suited for what we intend to do.  The class depends on the hardware available in your computer, if a high resolution timer is available is will use this, otherwise it will fall back to DateTime.Now.

You can check if the Stopwatch is using a high resolution timer by calling Stopwatch.IsHighResolution, and inquiry about the resolution in ticks per second by querying Stopwatch.Frequency.

// If we don't have a high resolution timer then Stopwatch will fall back
// to DateTime, which is much less reliable
if (Stopwatch.IsHighResolution)
Console.WriteLine("We have a high resolution timer available");

long frequency = Stopwatch.Frequency;
Console.WriteLine(" Timer frequency in ticks per second = {0}",frequency);

To start a Stopwatch simply call “Stopwatch.StartNew()” as shown below:

// Start the stopwatch
Stopwatch sw = Stopwatch.StartNew();

for (int Lp = 0; Lp < 100; Lp++)
Console.WriteLine("Hello World!");

// Stop the stopwatch

// Report the results
Console.WriteLine("Time used (float): {0} ms",sw.Elapsed.TotalMilliseconds);
Console.WriteLine("Time used (rounded): {0} ms",sw.ElapsedMilliseconds);

The ElapsedMilliseconds property returns a rounded number to the nearest full millisecond, the Elapsed.TotalMilliseconds property is a float that can return execution times to the partial millisecond.

Image credit: Stopwatch by Duy

Be Sociable, Share!

Tags: , , , ,

One Response to “Timing C# function performance with the Stopwatch class”

  1. George Says:

    Useful! Thanks!

Most popular

    Sorry. No data so far.

Recent Comments
  • Juan Romero: Hi there, it’s a neat little class, but I believe you could do the same thing with the WebClient...
  • anthosh: Hey, THank you very much for your tutorial. It was awesome. But i have a problem that i am not able to...
  • bian: how to get passphase if i have encrypt and decrypt string?? Thanks alot
  • Michael: Hi, I really like your post, thanks a lot, it really helped clear up a few things I could not remember how...
  • Bharat Prajapati: i was trying to import keyword dictionary to this plugin which is in csv format, but i get an error...