Simple profiler class for .NET applications

by dan 22. October 2008 01:32

The .NET framework provides easy access to the internal Windows high resolution timers which can be used to accurately measure microsecond-level time intervals.

This functionality is exposed by the StopWatch class. This class is relatively easy to use, but several pitfalls can be avoided by using the code attached to this article.

First, the StopWatch graciously downgrades to millisecond accuracy when Windows runs out of high resolution timers. These are expensive resources (~30 instances available). A naïve approach would probably consume too many kernel-level timers when working on large applications. Our code uses a single high resolution timer when timing an unlimited number of actions.

Extra hassle is implied when the timers are used in a multithreaded environment, as timing code should not have a negative impact on the execution.

This version is able to profile single actions or repeated ones. For the second case it computes total execution time, average, minimum and maximum. Results can be displayed to an external logger or used programmatically.

Examples can be found in the Program.cs file. Compile the project in RELEASE version to get interesting results.

By the way, I know you know concatenating strings with StringBuilder is faster than “+=” operator on a string.

But did you know it is actually 1000 times faster??

Use this code to check it by yourself

              Profiler.Start("using string operator +=");
            string big = "hello again ";
            for (int i = 0; i < 10000; i++)
            {
                big += "and again ";
            }
            Profiler.End();

            Profiler.Start("using StringBuilder");
            
            big = "hello again ";
            StringBuilder sb = new StringBuilder(big);
            for (int i = 0; i < 10000; i++)
            {
                sb.Append( "and again ");
            }
            big = sb.ToString();
            Profiler.End();

 

 

DOWNLOAD EXAMPLE PROJECT 

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

high performance computing

Comments

Add comment


(Will show your Gravatar icon)  

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen