Microbenchmarking C# code

Jeremy Tammik, from our DevTech EMEA team, pointed me to this useful and interesting site:

http://www.yoda.arachsys.com/csharp/benchmark.html

It introduces a very easy way to benchmark functions in your application by simply tagging them with a [Benchmark] attribute (you also need to have included the C# file posted on the above site in your project, of course).

Jeremy also highlighted a very pertinent paragraph in the above site:

Use local variables where possible.

The CLR can do a more optimisations on code which doesn't (for the most part) "escape" from just local variables. For instance, it doesn't need to worry about other threads tampering with the variables. That's the reason the second example copies the number of iterations into a local variable before running the loop, and copies the result out of a local variable into a class variable right at the very end. This may or may not make a significant difference to your test (on the current CLR), but I believe it's good practice anyway - although you need to bear this in mind when considering using the results in a real application!

That's it for this post - I'll be back on Friday with my last post before the New Year (assuming I manage to stay away from my computer during our annual, end-of-year office shut-down).

3 responses to “Microbenchmarking C# code”

  1. That looks like an excellent site! Well done to Jeremy for finding it and Kean for blogging it!

    Seasonal Greetings to all at DevTech, have a good shutdown and New Year period 🙂

  2. Nice "mini" profiler.

    For more comprehensive execution profiling, and assuming one doesn't have pockets deep enough for a high-end solution like like Rational Purify, have a look at this:

    softprodigy.com/...

  3. Someone else in my team also suggested looking at the "Visual Studio Performance Tool profiler". I haven't investigated any of these tools personally.

    Kean

Leave a Reply to Tony Tanzillo Cancel reply

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