Posted by: Cirilo Meggiolaro | 01/30/2009

Tip of the day #108 – Stopwatch class

Have you had to add a datetime object on a method body to check how long a code is taking to execute?

Available under the System.Diagnostics namespace, the Stopwatch class is a good utility to achieve this and other tasks where you need to measure the time elapsed between a start and an end point or within loops.

Properties

  • TimeSpan Elapsed: Gets a TimeSpan object that contains the total elapsed time measured by the Stopwatch instance;
  • long ElapsedMilliseconds: Gets the total elapsed time measured by the Stopwatch instance, in milliseconds;
  • long ElapsedTicks: Gets the total elapsed time measured by the Stopwatch instance, in timer ticks;
  • bool IsRunning: Gets a Boolean value that indicates whether the Stopwatch timer is running or not.

Methods

  • long GetTimestamp(): Gets the current number of ticks from the timer;
  • Reset(): Stops and resets the elapsed time to zero;
  • Start(): Starts, or resumes, measuring elapsed time;
  • Stopwatch StartNew(): Initializes a new Stopwatch, setting the elapsed time to zero and start it;
  • Stop(): Stops measuring elapsed time.

How to..

The methods and properties names say it all. The following code is commented:

/// A counter for demonstration purpose.
int counter = 10;

/// Declares and instantiate
/// a new Stopwatch object.
Stopwatch watch = new Stopwatch();

/// Starts the Stopwatch object.
watch.Start();

while (counter– > 0)
{
    /// A thread sleep for demonstration purpose.
    Thread.Sleep(300);

    /// Displays the elapsed time in seconds.
    Console.WriteLine(watch.Elapsed.TotalSeconds.ToString());

    /// Displays the elapsed timer ticks.
    Console.WriteLine(watch.ElapsedTicks.ToString());

    /// Displays the elapsed time in milliseconds.
    Console.WriteLine(watch.ElapsedMilliseconds.ToString());
}

/// Resets the Stopwatch.
watch.Reset();

/// At this moment, the Stopwatch is stopped.
/// To continue measuring time, you need to restart it.
watch.Start();

/// A thread sleep for demonstration purpose.
Thread.Sleep(300);

/// Displays the elapsed time in seconds.
Console.WriteLine(watch.Elapsed.TotalSeconds.ToString());

/// Stops the Stopwatch
watch.Stop();


Responses

  1. In the CF we use a lot the TickCount from System.Environment. Never heard of this class, very sophisticated…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: