In Visual Studio 2008, you can profile managed code using the Performance Tools that exists under the Analyze Menu. This allows you determine performance bottlenecks in code. There are two ways of doing this:
- Sampling – measures program state by sampling certain metrics such as clock cycles on a periodic basis.
- Instrumentation – inserts additional code into your code
This article discusses sampling. It is important to note that sampling can only be performed on a physical environment (i.e. not a VM).
To start profiling code, you must first enable collection of data using VSPerfCLREnv.cmd, typically located at C:\Program Files\Microsoft Visual Studio 9.0\Team Tools\Performance Tools. To enable CPU profiling, I run the above batch file with the option /globalsampleon. This enables sampling (attaching) to managed services. You can also enabled /globalsamplegc to profile memory. SImply run VSPerfCLREnv.cmd with no parameters to get the full list of options. Once this has been set, you need to perform a reboot, or restart all process that use dot net (at least i think – w3wp on its own was not sufficient).
Open the project you want to profile in Visual Studio and from the analyze menu select “Launch Performance Wizard”. Select the relevant project to profile from your current solution e.g
Select sampling as the profiling method
Click finish on the next screen
The performance explorer will now appear (note that you can add additional target projects to this). To start gathering performance data, simply right click the performance node and select “attach/detach”. Locate and attach to the W3WP (you may need to check the “Show Processes in All Sessions” and “Show Processes for all users checkboxes”.
Once attached, begin hitting your web application through the browser (suggestion – set up a load test to repeatedly hit multiple times). Click stop in the performance explorer window when complete. The results will then process to give you summary data.
Change the current view drop down to drill into the results. E.g. change to modules and scoll down to find modules appropriate to your code
Double click on relevant functions to drill into the details…
Note that you can order by “Inclusive Samples %” to get the most expensive function calls from your current function. Double click these functions to drill into these.