5

In here it is explained how to profile an .exe file in visual studio. Is there any way to profile a mex code using the same procedure?

Thanks.

Thoth
  • 993
  • 12
  • 36

1 Answers1

9

You sure can. Just enable generation of debug info (symbols) when building the MEX file, and attach to MATLAB.exe from the Analyze->Profile menu in Visual Studio.

It's nearly the same procedure as for debugging MEX files with Visual Studio. The process is trivial if you built the MEX file with a VS project (rather than the mex command), in which case you simply enable Profiling information in the project (Linker-Advanced-Profile property), build, and then attach to MATLAB.exe from the Analyze->Profiler->Attach/detach... menu item.

If you are building with mex from MATLAB, you need to enable building a MEX file with symbolic information, but also enable optimization:

mex -g -O -largeArrayDims myMEX.cpp

I generally build MEX files from VS projects rather than with mex, so I can't say how well this latter option works, but the documentation for the -O switch suggests that you can have optimization and symbolic information generation at the same time. EDIT: It may also require editing your mexopts.bat and adding /DEBUG /PROFILE (does not disable compiler optimizations!) to LINKFLAGS. This may also allow you to omit -g from mex, but I can't say.

EDIT 2: From R2014a, MEX options are no longer managed with .bat files. Instead, look for an XML file like C:\Users\Jon\AppData\Roaming\MathWorks\MATLAB\R2014a\mex_C_win64.xml.

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • Thanks for the response is really appreciated! `Generate Debug Info: Yes(\Debug)`, `Profile: Yes(PROFILE)` and then matlab is attached. A new tad appeared in the VS2010 with the message `Currently profiling` but is loading without end. Am I doing something wrong? PS: I have run the mex function during profiling. – Thoth Apr 24 '14 at 20:53
  • @Thoth That is correct, it is profiling when it has the perpetually rotating swirly thing. You need to detach to have VS report the results. Use the Performance Explorer (usually a tab on the left) to detach, or from the Analyze->Profiler menu. Sometimes _stopping_ instead of detaching can crash MATLAB. – chappjc Apr 24 '14 at 20:58
  • Do we have to run the mex function on the background, via matlab, while VS is profiling? – Thoth Apr 24 '14 at 21:04
  • @Thoth Yes, profiling essentially watches it run and looks at how frequently individual lines are observed executing. Stop profiling, make a new profiling session, attach, go to MATLAB and start the MEX file running, then when it's done go back to VS and detach. – chappjc Apr 24 '14 at 21:08
  • @chappjc What about MEX files not built from either VS or using the ```mex``` tool in MATLAB? What about ones compiled from an object file using g++ with -lmex and -lmx? When I attempted it, VS would hang forever when trying to analyze it. – Tyler Shellberg Jun 26 '19 at 22:02