| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Profiling is a way to measure where a program spends time. To assist you in profiling, MATLAB software provides a graphical user interface, called the Profiler, which is based on the results returned by the profile function. Once you identify which functions are consuming the most time, you can determine why you are calling them and look for ways to minimize their use and thus improve performance. It is often helpful to decide whether the number of times a particular function is called is reasonable. Because programs often have several layers, your code may not explicitly call the most time-consuming functions. Rather, functions within your code might be calling other time-consuming functions that can be several layers down in the code. In this case it is important to determine which of your functions are responsible for such calls.
Profiling helps to uncover performance problems that you can solve by:
Avoiding unnecessary computation, which can arise from oversight
Changing your algorithm to avoid costly functions
Avoiding recomputation by storing results for future use
When you reach the point where most of the time is spent on calls to a small number of built-in functions, you have probably optimized the code as much as you can expect.
Note When using the Parallel Computing Toolbox™ software, you can use the parallel profiler to profile parallel jobs. See Using the Parallel Profiler for details. |
Here is a general process you can follow to use the Profiler to improve performance in your M-files. This section also describes how you can use profiling as a debugging tool and as a way to understand complex M-files.
Note Premature optimization can increase code complexity unnecessarily without providing a real gain in performance. Your first implementation should be as simple as possible. Then, if speed is an issue, use profiling to identify bottlenecks. |
In the summary report produced by the Profiler, look for functions that used a significant amount of time or were called most frequently. See Profile Summary Report for more information.
View the detail report produced by the Profiler for those functions and look for the lines that use the most time or are called most often. See Profile Detail Report for more information.
You might want to keep a copy of your first detail report to use as a reference to compare with after you make changes, and then profile again.
Determine whether there are changes you can make to the lines most called or the most time-consuming lines to improve performance.
For example, if you have a load statement within a loop, load is called every time the loop is called. You might be able to save time by moving the load statement so it is before the loop and therefore is only called once.
Click the links to the files and make the changes you identified for potential performance improvement. Save the files and run clear all. Run the Profiler again and compare the results to the original report. Note that there are inherent time fluctuations that are not dependent on your code. If you profile the exact same code twice, you can get slightly different results each time.
The Profiler is a useful tool for isolating problems in your M-files.
For example, if a particular section of the file did not run, you can look at the detail reports to see what lines did run, which might point you to the problem.
You can also view the lines that did not run to help you develop test cases that exercise that code.
If you get an error in the M-file when profiling, the Profiler provides partial results in the reports. You can see what ran and what did not to help you isolate the problem. Similarly, you can do this if you stop the execution using Ctrl+C, which might be useful when a file is taking much more time to run than expected.
For lengthy M-files that you did not create or that you have not used for awhile and are unfamiliar with, you can use the Profiler to see how the M-file actually worked. Use the Profiler detail reports to see the lines actually called.
If there is an existing GUI tool (or M-file) similar to one that you want to create, start profiling, use the tool, then stop profiling. Look through the Profiler detail reports to see what functions and lines ran. This helps you determine the lines of code in the file that are most like the code you want to create.
Use the Profiler to help you determine where you can modify your code to make performance improvements. The Profiler is a tool that shows you where an M-file is spending its time. This section covers
For information about the reports generated by the Profiler, see Profile Summary Report and Profile Detail Report.
You can use any of the following methods to open the Profiler:
Select Desktop > Profiler from the MATLAB desktop.
Click the Profiler button
in the MATLAB desktop
toolbar.
With a file open in the MATLAB Editor, select Tools > Open Profiler.
Select one or more statements in the Command History window, right-click to view the context menu, and choose Profile Code.
Enter the following function in the Command Window:
profile viewer
The following illustration summarizes the typical steps for profiling.

To profile an M-file or a line of code, follow these steps:
If your system uses Intel® multi-core chips, you may want to restrict the active number of CPUs to one.
See Intel Multi-Core Processors — Setting for Most Accurate Profiling on Windows Systems for details.
In the Run this code field in the Profiler, type the statement you want to run.
You can run this example
[t,y] = ode23('lotka',[0 2],[20;20])
as the code is provided with MATLAB demos. It runs the Lotka-Volterra predator-prey population model. For more information about this model, type lotkademo, which runs the demonstration.
To run a statement you previously profiled in the current MATLAB session, select the statement from the list box—MATLAB automatically starts profiling the code, so skip to step 3.
Click Start Profiling (or press Enter after typing the statement).
While the Profiler is running, the Profile time indicator (at the top right of the Profiler window) is green and the number of seconds it reports increases.
![]()
When the profiling is finished, the Profile time indicator becomes dark red and shows the length of time the Profiler ran. The statements you profiled are shown as having been executed in the Command Window.
![]()
This is not the actual time that your statements took to run; it is the wall clock (or tic/toc) time elapsed from when you clicked Start Profiling until profiling stops. If the time reported is much different from what you expected (for example, hundreds of seconds for a simple statement), you might have had profiling on longer than you realized. This time also does not match the time reported in Profiler Summary report statistics, which is based on cpu time by default, not wall clock time. To view profile statistics based on wall clock time, use the profile function with the -timer real option as shown in Using the profile Function to Change the Time Type Used by the Profiler.
When profiling is complete, the Profile Summary report appears in the Profiler window. For more information about this report, see Profile Summary Report.
If you restricted the number of active CPUs in Step 1, reset the number of active CPUs to the original setting.
Intel Multi-Core Processors — Setting for Most Accurate Profiling on Windows Systems. If your system uses Intel multicore chips, and you plan to profile using CPU time, set the number of active CPUs to one before you start profiling. This results in the most accurate and efficient profiling.
Open Windows Task Manager.
On the Processes tab, right-click MATLAB.exe and then click Set Affinity.
The Processor Affinity dialog box opens.
In the Processor Affinity dialog box, note the current settings, and then clear all the CPUs except one.
Your Processor Affinity dialog box should appear similar to the following image:

Click OK.
Reset the state of the Profiler so that it recognizes the processor affinity changes you made. The easiest way to do this is to change the Profiler timer setting from real and then back to cpu, by issuing the following in the Command Window:
profile -timer real profile -timer cpu
Remember to set the number of CPUs back to their original settings when you finish profiling by rerunning the preceding steps, and restoring the original selections in the Processor Affinity dialog box in Step 3.
You can run the Profiler for a graphical user interface, such as the Filter Design and Analysis tool included with Signal Processing Toolbox. You can also run the Profiler for an interface you created, such as one built using GUIDE.
To profile a graphical user interface, follow these steps:
In the Profiler, click Start Profiling. Make sure that no code appears in the Run this code field.
Start the graphical user interface. (If you do not want to include its startup process in the profile, do not click Start Profiling, step 1, until after you have started the graphical interface.)
Use the graphical interface. When you are finished, click Stop Profiling in the Profiler.
The Profile Summary report appears in the Profiler.
To profile more than one statement, follow these steps:
In the Profiler, clear the Run this code field and click Start Profiling.
In the Command Window, enter and run the statements you want to profile.
After running all the statements, click Stop Profiling in the Profiler.
The Profile Summary report appears in the Profiler.
To change the fonts used in the Profiler, follow these steps:
Select File > Preferences > Fonts to open the Font Preferences dialog box.
In the Font Preferences dialog box, select the code or text font that you want to use in the Profiler. The Profiler is an HTML Proportional Text tool. For more information, click the Help button in the dialog box.
The Profile Summary report presents statistics about the overall execution of the function and provides summary statistics for each function called. The report formats these values in four columns.
Function Name — A list of all the functions and subfunctions called by the profiled function. When first displayed, the functions are listed in order by the amount of time they took to process. To sort the functions alphabetically, click the Function Name link at the top of the column.
Calls — The number of times the function was called while profiling was on. To sort the report by the number of times functions were called, click the Calls link at the top of the column.
Total Time — The total time spent in a function, including all child functions called, in seconds. The time for a function includes time spent on child functions. To sort the functions by the amount of time they consumed, click the Total Time link at the top of the column. By default, the summary report displays profiling information sorted by Total Time. Note that the Profiler itself uses some time, which is included in the results. Also note that total time can be zero for files whose running time was inconsequential.
Self Time — The total time spent in a function, not including time for any child functions called, in seconds. If MATLAB can determine the amount of time spent for profiling overhead, MATLAB excludes it from the self time also. (MATLAB excludes profiling overhead from the total time and the time for individual lines in the Profile Detail Report as well.)
The bottom of the Profiler page contains a message similar to one of the following, depending on whether MATLAB can determine the profiling overhead:
Self time is the time spent in a function excluding both the time spent in its child functions and most of the overhead resulting from the process of profiling. In the present run, self time excludes 0.240 seconds of profiling overhead. The amount of remaining overhead reflected in self time cannot be determined, and therefore is not excluded.
Self time is the time spent in a function excluding the time spent in its child functions. Self time also includes some overhead resulting from the process of profiling.
To sort the functions by this time value, click the Self Time link at the top of the column.
Total Time Plot — Graphic display showing self time compared to total time.
Following is the summary report for the Lotka-Volterra model described in Example: Using the profile Function.
To print a summary report, click the Print button
.
To get more detailed information about a particular function, click its name in the Function Name column. See Profile Detail Report for more information.

The Profile Detail report shows profiling results for a selected
function that was called during profiling. A Profile Detail report
is made up of seven sections, summarized below. By default, the Profile
Detail report includes all seven sections, although, depending on
the function, not every section contains data. To return to the Profile
Summary report from the Profile Detail report, click the Home button
in the toolbar. The following
sections provide more detail:
You can determine which sections are included in the display by selecting them and then clicking the Refresh button. The following sections provide more detail about each section of this report.

The detail report header includes the name of the function that was profiled, the number of times it was called in the parent function, and the amount of time it used.
The header includes a link that opens the function in your default text editor.
The header also includes a link that copies the report to a separate window. Creating a copy of the report can be helpful when you make changes to the file, run the Profiler for the updated file, and compare the Profile Detail reports for the two runs. Do not make changes to M-files provided with products from The MathWorks, that is, files in matlabroot/toolbox folders.

To include the Parents section in the detail report, select the Show parent functions check box. This section of the report provides information about the parent functions, with links to their detail reports.

To include information about the lines of code that used the most amount of processing time in the detail report, select the Show busy lines check box. Note that this was not selected in the example. Click a line number to view that line of code in the source listing.

To include the Children section of the detail report, select the Show child functions check box. This section of the report lists all the functions called by the profiled function. If the called function is an M-file, you can view the source code for the function by clicking its name.

To include the M-Lint results section in the detail report display, select the Show M-Lint results check box. This section of the report provides information about problems and potential improvements, generated by M-Lint about the function. For more information about M-Lint, see M-Lint Code Check Report.

To include the Coverage results section in the detail report display, select the Show file coverage check box. This section of the report provides statistical information about the number of lines in the code that executed during the profile run.

To include the Function listing section in the detail report display, select the Show function listing check box. If the file is an M-file, the Profile Detail report includes a column listing the execution time for each line, a column listing the number of times the line was called, and the source code for the function.
In the function listing, comment lines appear in green, lines of code that executed appear in black, and lines of code that did not execute appear in gray. If you click a function name in the listing, you can view its detail report.
By default, the Profile Detail report uses the color red to highlight the lines of code with the longest execution time. The darker the shade of red, the longer the line of code took to execute. Using the menu in this section of the detail report you can change this default and choose to highlight lines of code based on other criteria such as the lines called the most, lines called out by M-Lint, or lines of code that were (or were not) executed. Using this menu, you can also turn off highlighting completely.

The Profiler is based on the results returned by the profile function. The profile function provides some features that are not available in the GUI. For example, using the function, you can specify that the statistics display the time it takes for statements to run as clock time instead of CPU time.
This section includes the following topics with respect to the profile function:
This example demonstrates how to run profile:
To start profile, type in the Command Window
profile on
Execute an M-file. This example runs the Lotka-Volterra predator-prey population model. For more information about this model, type lotkademo, which runs a demonstration.
[t,y] = ode23('lotka',[0 2],[20;20]);
Generate the profile report and display it in the Profiler window. This suspends profile.
profile viewer
Restart profile, without clearing the existing statistics.
profile resume
The profile function is now ready to continue gathering statistics for any more M-files you run. It will add these new statistics to those generated in the previous steps.
Stop profile when you finish gathering statistics.
profile off
To view the profile data, call profile specifying the 'info' argument. The profile function returns data in a structure.
p = profile('info')
p =
FunctionTable: [10x1 struct]
FunctionHistory: [2x0 double]
ClockPrecision: 3.3333e-010
ClockSpeed: 3.0000e+009
Name: 'MATLAB'
The FunctionTable indicates that statistics were gathered for 10 functions.
To save the profile report, use the profsave function. This function stores the profile information in separate HTML files, for each function listed in FunctionTable of p.
profsave(p)
By default, profsave puts these HTML files in a subfolder of the current folder named profile_results, and displays the summary report in your system browser. You can specify another folder name as an optional second argument to profsave.
The profile function returns results in a structure. This example illustrates how you can access these results:
To start profile, specifying the history option, type in the Command Window.
profile on -history
The history option specifies that the report include information about the sequence of functions as they are entered and exited during profiling.
Execute an M-file. This example runs the Lotka-Volterra predator-prey population model. For more information about this model, type lotkademo, which runs a demonstration.
[t,y] = ode23('lotka',[0 2],[20;20]);
profile off
Get the structure containing profile results.
stats = profile('info')
stats =
FunctionTable: [43x1 struct]
FunctionHistory: [2x754 double]
ClockPrecision: 3.3333e-010
ClockSpeed: 3.0000e+009
Name: 'MATLAB'
The FunctionTable field is an array of structures, where each structure represents an M-function, M-subfunction, MEX-function, or, because the builtin option is specified, a MATLAB built-in function.
stats.FunctionTable
ans =
41x1 struct array with fields:
CompleteName
FunctionName
FileName
Type
NumCalls
TotalTime
TotalRecursiveTime
Children
Parents
ExecutedLines
IsRecursive
PartialData
View the second structure in FunctionTable.
stats.FunctionTable(2)
ans =
CompleteName: [1x79 char]
FunctionName: 'ode23'
FileName: [1x73 char]
Type: 'M-function'
NumCalls: 1
TotalTime: 0.3902
TotalRecursiveTime: 0
Children: [20x1 struct]
Parents: [0x1 struct]
ExecutedLines: [139x3 double]
IsRecursive: 0
PartialData: 0
To view the history data generated by profile, view the FunctionHistory, for example, stats.FunctionHistory. The history data is a 2-by-n array. The first row contains Boolean values, where 0 (zero) means entrance into a function and 1 means exit from a function. The second row identifies the function being entered or exited by its index in the FunctionTable field. To see how to create a formatted display of history data, see the example on the profile reference page.
To save the profile report, use the profsave function.
This function stores the profile information in separate HTML files, for each function listed in the FunctionTable field of the structure, stats.
profsave(stats)
By default, profsave puts these HTML files in a subfolder of the current folder named profile_results. You can specify another folder name as an optional second argument to profsave.
profsave(stats,'mydir')
By default, MATLAB generates the Profiler Summary report using CPU time, as opposed to real (wall clock) time. This example illustrates how you can direct MATLAB to use real time instead.
The following image shows the Profiler Summary report as it appears by default, using CPU time:

Specify that the Profiler use real time instead, by using the profile function with the -timer real option, as shown in this example:
If the Profiler is currently open, close the Profiler, and if prompted, stop profiling.
Set the timer to real time by typing the following in the Command Window:
profile on -timer real
Run the M-file that you want to profile. This example runs the Lotka-Volterra predator-prey population model.
[t,y] = ode23('lotka',[0 2],[20;20]);
Open the Profiler by typing the following in the Command Window:
profile viewer
The Profiler opens and indicates that real time is being used, as shown in the following image:

To change the timer back to using CPU time:
Close the Profiler, and if prompted, stop profiling.
Type the following in the Command Window:
profile on -timer cpu
Type the following in the Command Window to reopen the Profiler:
profile viewer
![]() | M-Lint Code Check Report | Publishing M-Files | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |