Main Content

Profile Your Code to Improve Performance

What Is Profiling?

Profilingis a way to measure the time it takes to run your code and identify where MATLAB®spends the most time. After you identify which functions are consuming the most time, you can evaluate them for possible performance improvements. You also can profile your code to determine which lines of code do not run. Determining which lines of code do not run is useful when developing tests for your code, or as a debugging tool to help isolate a problem in your code.

You can profile your code interactively using the MATLAB Profiler or programmatically using theprofilefunction. For more information about profiling your code programmatically, seeprofile. If you are profiling code that runs in parallel, for best results use the Parallel Computing Toolbox™ parallel profiler. For details, seeProfiling Parallel Code(Parallel Computing Toolbox).

Tip

Code that is prematurely optimized can be unnecessarily complex without providing a significant gain in performance. Make your first implementation as simple as possible. Then, if speed is an issue, use profiling to identify bottlenecks.

Profile Your Code

To profile your code and improve its performance, use this general process:

  1. Run the Profiler on your code.

  2. Review the profile summary results.

  3. Investigate functions and individual lines of code.

    For example, you may want to investigate functions and lines of code that use a significant amount of time or that are called most frequently.

  4. Save the profiling results.

  5. Implement potential performance improvements in your code.

    For example, if you have aload声明在一个loop, you might be able to move theloadstatement outside the loop so that it is called only once.

  6. Save the files, and runclear all. Run the Profiler again and compare the results to the original results.

  7. Repeat the above steps to continue improving the performance of your code. When your code spends most of its time on calls to a few built-in functions, you have probably optimized the code as much as possible.

Run the Profiler on Your Code

To run the Profiler on a line of code:

  1. Open the Profiler by going to theAppstab, and underMATLAB, clicking the Profiler app icon. You also can typeprofile viewerin the Command Window.

  2. Go to theProfilertab, and in theProfilesection, enter the code that you want to profile in the edit box.

    For example, create a functionsolvelotka.mthat finds the prey and predator population peaks for the Lotka-Volterra example provided with MATLAB:

    function [preypeaks,predatorpeaks] = solvelotka(t0, tfinal, y0) [~,y] = ode23(@lotka,[t0 tfinal],y0); preypeaks = calculatepeaks(y(:,1)); predatorpeaks = calculatepeaks(y(:,2)); end function peaks = calculatepeaks(A) [TF,P] = islocalmax(A); peaks = P(TF); end
    Enter this statement in the edit box to profile thesolvelotkafunction:
    [preypeaks,predatorpeaks] = solvelotka(0,15,[20;20])

    If you previously profiled the statement in the current MATLAB session, you also can select it from the edit box drop down list.

  3. ClickRun and Time.

    When profiling is complete, the Profiler displays the results in Profile Summary. The statements you profiled also display as having been run in the Command Window.

To profile a code file open in the Editor, on theEditortab, in theRunsection, selectRun>Run and Time. The Profiler profiles the code file open in the current Editor tab and displays the results in the Profile Summary.

Review the Profile Summary Results

After running the Profiler on your code, the Profile Summary presents statistics about the overall execution of your code and provides summary statistics for each function called. For example, the image below shows the Profile Summary for thesolvelotkafunction.

At the top of the Profile Summary results, a flame graph shows a visual representation of the time MATLAB spent running the code. Each function that was run is represented by a bar in the flame graph. User-defined functions display in blue, and MathWorks®functions display in gray.

The functions in the graph display in hierarchical order, with parent functions appearing lower on the graph, and child functions appearing higher on the graph. The bar that spans the entire bottom of the graph labeledProfile Summaryrepresents all of the code that ran. The width of a bar on the graph represents the amount of time it took for the function to run as a percentage of the total run time.

To see the actual percentage and time values as well as the full function name, hover over the bar in the graph. To display detailed information about a function including information about individual code lines, click the bar representing that function.

The function table below the flame frame displays similar information to the flame graph. Initially the functions appear in order of time they took to process. This table describes the information in each column.

Column Description
Function Name

Name of the function called by the profiled code.

Calls

Number of times the profiled code called the function.

Total Time

Total time spent in the function, in seconds. The time for the function includes time spent in child functions. The Profiler itself takes some time, which is included in the results. The total time can be zero for files whose run time is inconsequential.

自我的时间

Total time in seconds spent in a function, excluding time spent in any child functions. Self time also includes some overhead resulting from the process of profiling.

Total Time Plot

Graphic display showing self time compared to total time.

To sort the function table by a specific column, click the arrow in the column header. For example, click the arrow in theFunction Namecolumn to sort the functions alphabetically. Initially the results appear in order byTotal Time. To display detailed information about a function including information about individual code lines, click the function name.

Investigate Functions and Individual Code Lines

To find potential improvements in your code, look for functions in the flame graph or function table that use a significant amount of time or that are called most frequently. Click a function name to display detailed information about the function, including information about individual code lines. For example, click thesolvelotka>calculatepeaksfunction. The Profiler displays detailed information for the function.

At the top of the page, next to the name of the current function, the Profiler displays the number of times the function was called by a parent function and the total time spent in the function. Use the displayed links underneath the flame graph to open the function in your default editor or copy the displayed results to a separate window.

To return to the Profile Summary, in theProfilertab, click theProfile Summarybutton. You also can click theProfile Summarybar at the bottom of the flame graph.

Once you have clicked an individual function, the Profiler displays additional information in these sections:

Section Details
火焰图像

Flame graph showing visual representation of the time MATLAB spent running the profiled function. The graph shows the hierarchy of the profiled function, including child functions (displayed above the current function) and parent functions (displayed below the current function). User-defined functions display in blue (), and MathWorks functions display in gray ().

Hover over the bar in the graph to see the actual percentage and time values as well as the full function name. Click a bar representing a function to display detailed information about the function.

Parents

List of functions that call the profiled function, including the number of times the parent function called the profiled function.

Click a function name in the list to display detailed information about the function.

Lines that take the most time

List of code lines in the profiled function that used the greatest amount of processing time.

Click a code line to see it in theFunction Listingsection, within the context of the rest of the function code.

Children

所有的函数列表lled by the profiled function.

Click a function name in the list to display detailed information about the function.

Code Analyzer results

List of problems and potential improvements for the profiled function.

Coverage results

Code coverage statistics about the lines of code in the function that MATLAB executed while profiling.

打开分析器覆盖率报告,在曲线nt Folder browser, navigate to the folder containing the profiled code. Right-click in white space, and then selectReports>Coverage Report.

To perform additional code coverage analysis for your code, seeGenerate Code Coverage Report in HTML Format.

Function listing

Source code for the function, if it is a MATLAB code file.

For each line of code, theFunction listingincludes these columns:

  • Execution time for each line of code

  • Number of times that MATLAB executed the line of code

  • The line number.

    Click a line number in theFunction listingto open the function in your default editor.

  • The source code for the function. The color of the text indicates the following:

    • Green — Commented lines

    • Black — Executed lines of code

    • Gray — Non-executed lines of code

By default, the Profiler highlights lines of code with the longest execution time. The darker the highlighting, the longer the line of code took to execute. To change the highlighting criteria, go to theProfilertab, and in theViewsection, clickHighlight. Select from the available highlighting options. For example, to highlight lines of code that did not run, select theNon coverageoption.

Save Your Results

To compare the impact of changes after you have made improvements to your code, save your profiling results. To save your results, use the displayed link underneath the flame graph to copy the displayed results to a separate window.

You also can print your results from the Profiler by going to theProfilertab and clicking thePrintbutton.

Profile Multiple Statements in Command Window

To profile more than one statement in the Command Window:

  1. Go to the Command Window and typeprofile on.

  2. Enter and run the statements that you want to profile.

  3. After running all of the statements, typeprofile off.

  4. Open the Profiler by typingprofile viewer. You also can go to theAppstab, and underMATLAB,单击分析器的应用图标。

  5. Review the Profile Summary results.

Profile an App

You can profile apps that you create in App Designer. You also can profile apps that ship with MathWorks products, such as the Filter Design and Analysis tool included with Signal Processing Toolbox™.

To profile an app:

  1. Open the Profiler by going to theAppstab, and underMATLAB, clicking the Profiler app icon. You also can typeprofile viewerin the Command Window.

  2. In theProfilesection of the Profiler toolstrip, clickStart Profiling. Make sure that there is no code in the edit box to the right of the button.

  3. Start the app.

  4. Use the app.

  5. When you are finished, clickStop Profilingin the Profiler toolstrip.

  6. Review the Profile Summary results.

Note

To exclude the app startup process in the profile, reverse steps 2 and 3. In other words, start the app before you clickStart Profiling.

See Also

Apps

Functions

Related Topics