Main Content

技术to Improve Performance

To speed up the performance of your code, consider these techniques.

Environment

Be aware of background processes that share computational resources and decrease the performance of your MATLAB®code.

Code Structure

组织代码的同时:

  • Use functions instead of scripts. Functions are generally faster.

  • Prefer local functions over nested functions. Use this practice especially if the function does not need to access variables in the main function.

  • Use modular programming. To avoid large files and files with infrequently accessed code, split your code into simple and cohesive functions. This practice can decrease first-time run costs.

Programming Practices for Performance

Consider these programming practices to improve the performance of your code.

  • Preallocate — Instead of continuously resizing arrays, consider preallocating the maximum amount of space required for an array. For more information, see预先分配

  • Vectorize — Instead of writing loop-based code, consider using MATLAB matrix and vector operations. For more information, seeVectorization

  • Place independent operations outside loops — If code does not evaluate differently with eachfor要么whileloop iteration, move it outside of the loop to avoid redundant computations.

  • Create new variables if data type changes — Create a new variable rather than assigning data of a different type to an existing variable. Changing the class or array shape of an existing variable takes extra time to process.

  • 使用短路操作员 - 使用短路逻辑运算符,&&||若有可能。短路更有效,因为MATLAB仅在第一个操作数未完全确定结果时才评估第二操作数。有关更多信息,请参阅Logical Operators: Short Circuit

  • Avoid global variables — Minimizing the use of global variables is a good programming practice, and global variables can decrease performance of your MATLAB code.

  • Avoid overloading built-ins — Avoid overloading built-in functions on any standard MATLAB data classes.

  • Avoid using “data as code” — If you have large portions of code (for example, over 500 lines) that generate variables with constant values, consider constructing the variables and saving them, for example, in a MAT-file or。csvfile. Then you can load the variables instead of executing code to generate them.

Tips on SpecificMATLABFunctions

在编写绩效关键代码时,请考虑特定MATLAB函数的以下提示。

  • Avoid clearing more code than necessary. Do not use明确allprogrammatically. For more information, see明确

  • Avoid functions that query the state of MATLAB such asinputname,which,whos,exist(var), anddbstack。运行时内部内省是计算昂贵的。

  • Avoid functions such aseval,evalc,evalin, andFeval.(fname)。Use the function handle input toFeval.whenever possible. Indirectly evaluating a MATLAB expression from text is computationally expensive.

  • Avoid programmatic use ofcd,addpath., andrmpath, when possible. Changing the MATLAB path during run time results in code recompilation.

相关话题