A cool new timing class new to .NET 2.0

There is a new timing class called StopWatch which is in the .NET 2.0 framework in the System.Diagnostic namespace that is really handy for making timing measurements in your code. Previous managed code methods of doing timing like DataTime.Now() (which has a resolution of 10ms) or Environment.TickCount() (which has a resolution of 1ms) just didn’t have very good resolution in some cases. The StopWatch class now gives you the ability to have a resolution of nanoseconds which is comparable to the Win32 API calls of QueryPerformanceFrequency and QueryPerformanceCounter. So let’s look at some code that uses this new class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExe
{
    class Program
    {
        static void Main(string[] args)
        {
            //initialize the stopwatch class
            Stopwatch stopWatch = new Stopwatch();
           
            List testList = new List();
           
            //start the timer
            stopWatch.Start();

            for (int i = 100; i < 100; i++)
            {
                testList.Add(i.ToString());
                System.Threading.Thread.Sleep(10);
            }

            //end the timer
            stopWatch.Stop();
           
            //get the elapsed time
            TimeSpan timeSpan = stopWatch.Elapsed;
           
            //write the time out.
            Console.WriteLine(“Total time was: ” + timeSpan.ToString());
       
            Console.ReadLine();
        }
    }
}

What the code is doing is creating the StopWatch class and then adding some random entries into a list. The pattern you will use is to start the StopWatch do some work then stop it. Then you have the ability to get the elapsed time represented by a TimeStamp value using the Elapsed property, the elapsed time in milliseconds using the ElapsedMilliseconds property and finally the number of ticks using the ElapsedTicks property. It was interesting that they didn’t have a nanosecond property which would have been helpful. In this sample you will see I used ToString to show the nanoseconds due to TimeStamp not having a property that could show that low of a value.

Leave a Reply

Your email address will not be published. Required fields are marked *