Stopwatch – a timing function in C#

Recently while seeking inspiration, I found a small function in the .net api called StopWatch. It was exactly what I have been looking for. It is placed under System.Diagnostics.Stopwatch

Until now I have made my timed my solution algorithms using multiple timestamp variables, but I have come to realise that the StopWatch is exactly what I needed, and packs all the features I need.

It is rather straight forward to implement, and a code snippet for it might look like

Stopwatch clock = new Stopwatch();
clock.Start();
// Some operation
clock.Stop();
int elapsedTime = clock.ElapsedMilliseconds;

Based on the value of the IsHighResolution property of the StopWatch, the timing resolution will be significantly higher than the method with timestamps I have used previously.

It is possible to boiler the above code down to

Stopwatch clock = Stopwatch.StartNew();
// Some operation
clock.Stop();
int elapsedTime = clock.ElapsedMilliseconds;

Where the StartNew method creates a new StopWatch object and starts it.
Nothing fancy, just thought I would share my find with you.

Posted by Kristian

4 comments

can it be used as a timer (to make an action occure only for 5 seconds)?
and if so, how?

Hi Alon

I do believe that there are readers of this blog that can answer this much better than I can, Suprdewd as an example.

But my guess is no, that is not the purpose and I don’t think that is the right tool for it. I would much rather use threads for something like that.

thanks…. btw, i got to your blog by searching answers to poject euler and i loved it! keep up the good work 😀

Bjarki Ágúst

Maybe a bit late, but I just noticed the comment.

I would probably use threading to make an action run for 5 seconds. Something like:

static void SomeAction()
{
    // Do some work
    int number = 1;
    while (true)
    {
        Console.WriteLine(number);
        number++;
    }
}

static void Main(string[] args)
{
    // Create a thread object
    Thread thread = new Thread(SomeAction);

    // Start the worker thread
    thread.Start();

    // Wait 5 seconds on the main thread
    Thread.Sleep(5000);

    // Stop the worker thread
    thread.Abort();
}

Leave a Reply