Profiling Tip #2: Managed Code profiling and the command line

The most common question that comes in to the internal profiler by far is "Why am I not seeing any managed code in my profiles?"  Most of the internals who use our profiler like to do profile collection using the command line tools.  The reason why this is the most common mode of operation is that they want to collect data on their lab machines that generally don't have Visual Studio on them.   I'm sure this will be the primary mode for folks outside of the company as well.

This post on the profiler blog gives the basics of how this is done. 

The mistake people always make is they leave out the call to vsperfclrenv.cmd. This step is crucial to get managed code profiling to work. Let me go into it in a little more detail. Here's the usage:

Usage: VSPerfCLREnv [/?]
[/sampleon|/samplegc|/samplegclife|
/traceon |/tracegc |/tracegclife |
/globalsampleon|globalsamplegc|globalsamplegclife|
/globaltraceon |/globaltracegc|/globaltracegclife|
/off|/globaloff]

What this script actually does is set up some environment variables and registry values to allow the injection of our clr profiling dll in to managed processes.  In the most basic command line scenario, you start a cmd window.   Now type vsperfclrenv /sampleon.  This sets up the environment variables necessary in that cmd window and any app launched from that window will inherit those environment variables and can be profiled.

Sometimes however, you need to profile a dll that is loaded in to a service or some other app that you can't just launch from a cmd window such as an ASP.Net page.  In these cases, you can use vsperfclrenv /globalsampleon.  This will setup some registry keys that will make EVERY managed app load our dll.  You will probably have to reboot to complete this process.  You can double check to make sure that vsperfcorprof.dll is in your process using any tool that lists the dlls loaded in a process.  I personally use Process Explorer from SysInternals.com.   On the Process Explorer menu, View->LowerPaneView->Dlls should get you the info that you need.  Just to complicate this just a little further, vsperfcorprof.dll will load when the first managed function is hit.  So if you have a mixed mode app that starts native, and then loads a managed component, you might not immediately see vsperfcorprof.dll.