Timing Managed code in .NET


Lets start off with a simple, yet quite useful article on Timing Managed code. I will be using this in my future articles to test performance of certain pieces of code. A lot of sites mention the use of WIN32 functions QueryPerformanceCounter and QueryPerformanceFrequency. They provide timing results with nano-second accuracy. Here's a good article if you guys wanna try out timing managed code using these functions. http://msdn2.microsoft.com/en-us/library/ms979201.aspx

However, using these functions is quite inconvenient. Starting with .NET 2.0 comes the StopWatch class(also included in .NET 3.0).
Since all Windows systems that support .NET also include a high-resolution performance counter, you can pretty much count on the Stopwatch being a high-resolution timer. If you’re unsure, check the static Stopwatch.IsHighResolution property, which will tell you whether the timer is based on a high-resolution performance counter.
Check out http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch(vs.80).aspx for information on StopWatch class. The only problem with StopWatch class is that you need to reset the timer everytime you use start and stop methods.Thats because StopWatch accumulates timing values.

Here is the code

            long Frequency, Ticks, TotalTime;
            Stopwatch sw = new Stopwatch();
            Frequency = Stopwatch.Frequency;
            sw.Start();
            // your code goes here
            sw.Stop();
            Ticks = sw.ElapsedTicks;
            TotalTime=1000000L*Ticks/Frequency;
            Console.WriteLine("Total time in microseconds "+TotalTime);


Here, Frequency is returned as ticks/sec. So if you want time in nano-seconds use 10^9 instead of 10^6 in the TotalTime formula.
Also StopWatch frequency depends on the installed hardware and operating system, hence the Frequency value remains constant while the system is running. 


Skip to main content