Friday, 3 September 2010

Performance Measurement of .NET Code

Performance Measurement of .NET Code
In .NET we often come across scenarios where we need to find out how much time the code takes to execute, and find the exact location in the code where the performance is not good.
Especially when you are working customer facing applications like website or webservices.


Avoid Using DateTime
When I was new in development, I was using datetime most of the time. I was using the following code to check the execution time:

          
The above code works fine but its not very accurate.
I was working on a project where I was using CLR Store proc in SQL Server 2008 to call a webservice. I put the above code around it to
find out the execution time. It was taking about 400ms to execute the code. But in when I found the execution time for the store proc itself
in t-sql, it was taking about 1.4 second. At that time I realised that using DateTime is not a reliable method to find the execution time.

Use Stopwatch
As an alternative to this, I found that the .NET Framework already has a Stopwatch which is more accurate than DateTime.
I replaced my code with stopwatch and it give me accurate execution time.




___________________________________________________________________
Mitul Patel
http://dot-net-solutions.blogspot.com/
http://www.omkarsolutions.com.au/
___________________________________________________________________

I recommend the following books to improve your code performance.