Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Profiling for Improving Performance

What Is Profiling?

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:

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.

Profiling Process and Guidelines

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. Repeat this process to continue improving the performance.

Using Profiling as a Debugging Tool

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.

Using Profiling for Understanding an M-File

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.

Using the Profiler

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.

Opening the Profiler

You can use any of the following methods to open the Profiler:

Running the Profiler

The following illustration summarizes the typical steps for profiling.

Image of Profiler showing steps to run it. 1, Type provide viewer to open the Profiler. 2, Type the statement to run in the Run this code field of the Profiler. 3, click Start Profiling.

To profile an M-file or a line of code, follow these steps:

  1. 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.

  2. 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.

  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.

    Image of Profile time indicator, colored green to indicate that the Profiler is running, and showing the profile time currently as 4 seconds.

    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.

    Image of Profile time indicator, colored black indicating that profiling has stopped, and showing the total time of 6 seconds.

    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.

  4. When profiling is complete, the Profile Summary report appears in the Profiler window. For more information about this report, see Profile Summary Report.

  5. 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.

  1. Open Windows Task Manager.

  2. On the Processes tab, right-click MATLAB.exe and then click Set Affinity.

    The Processor Affinity dialog box opens.

  3. 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:

  4. Click OK.

  5. 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.

Profiling a Graphical User Interface

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:

  1. In the Profiler, click Start Profiling. Make sure that no code appears in the Run this code field.

  2. 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.)

  3. Use the graphical interface. When you are finished, click Stop Profiling in the Profiler.

    The Profile Summary report appears in the Profiler.

Profiling Statements from the Command Window

To profile more than one statement, follow these steps:

  1. In the Profiler, clear the Run this code field and click Start Profiling.

  2. In the Command Window, enter and run the statements you want to profile.

  3. After running all the statements, click Stop Profiling in the Profiler.

    The Profile Summary report appears in the Profiler.

Changing Fonts for the Profiler

To change the fonts used in the Profiler, follow these steps:

  1. Select File > Preferences > Fonts to open the Font Preferences dialog box.

  2. 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.

  3. Click Apply or OK. The Profiler font reflects the changes.

Profile Summary Report

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.

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 Image of 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.

Image of Profile Summary report, highlighting key features. Click any column name to sort by that column. Click any function name to display the detailed report.

Profile Detail Report

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 Image of Home button. in the toolbar. The following sections provide more detail:

Controlling the Contents of the Detail Report Display

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.

Image of Profiler detail report and options for it.

Profile Detail Report Header

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.

Image of header in the Profile detail report, highlighting main features. Click the M-function in file link to the file in the default editor. Click Copy to new window to copy the detail report to a new window.

Parent Functions

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.

Image of Profile detail report showing parents (calling functions). Click a file name to show that parent file's detail report.

Busy Lines

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.

Image of Profile detail report with Show busy lines selected. Five lines are shown, and there is an entry for other lines and overhead. Click one of the lines to go to that line in the file.

Child Functions

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.

Image of children portion of Profile detail report.

M-Lint Results

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.

Image of Profile detail report showing M-Lint results section.

File Coverage

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.

Image of Profile report showing file coverage section.

Function Listing

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.

Image of Profile detail report with File listing section shown.

The profile Function

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:

Example: Using the profile Function

This example demonstrates how to run profile:

  1. To start profile, type in the Command Window

    profile on
    
  2. 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]);
    
  3. Generate the profile report and display it in the Profiler window. This suspends profile.

    profile viewer 
    
  4. 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.

  5. Stop profile when you finish gathering statistics.

    profile off
    
  6. 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.

  7. 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.

Accessing profile Function Results

The profile function returns results in a structure. This example illustrates how you can access these results:

  1. 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.

  2. 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]);
    
  3. Stop profiling.

    profile off
    
  4. 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'
    
  5. 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
    
  6. 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
    
  7. 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.

Saving profile Function Reports

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')

Using the profile Function to Change the Time Type Used by the Profiler

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:

  1. If the Profiler is currently open, close the Profiler, and if prompted, stop profiling.

  2. Set the timer to real time by typing the following in the Command Window:

    profile on -timer real
    
  3. 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]);
    
  4. 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:

  5. To change the timer back to using CPU time:

    1. Close the Profiler, and if prompted, stop profiling.

    2. Type the following in the Command Window:

      profile on -timer cpu
      
    3. Type the following in the Command Window to reopen the Profiler:

      profile viewer
      
  


Recommended Products

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