matlab提速技巧


1首先要学会用profiler分析代码效率.

1.1. 打开profiler.

在matlab下,Desktop->Profiler.

或在M文件编辑器下,Tools->Open Profiler.

1.2. 运行profiler

可以把要运行的code拷入Run this code后面的输入框里。

例如:

[t,y] = ode23('lotka',[0 2],[20;20])

也可以输入要运行的M文件名。

After that, click Start Profiling (or press Enter after entering the statement).

1.3. 查看Profile Detail Report

     它将会告知你哪些代码消耗了多少时间,可以找到哪些函数或那些代码行消耗了主要的时间,或者是经常被调用。可以按calls/Total Time/Self Time进行排序显示。

也可以用stopwatch Timer函数,计算程序消耗时间

Use tic and toc as shown here.

tic

   - run the program section to be timed -

toc

2、加速方法1——向量化编程

     

  MATLAB programs are interpretted. This would seem to make it inapproapriate for large scale scientific computing. The power of MATLAB is realized with its extensive set of libraries which are compiled or are carefully coded in MATLAB to utilize "vectorization". The concept of vectorization is central to understanding how to write efficient MATLAB code.

     Vectorized code takes advantage, wherever possible, of operations involving data stored as vectors. This even applies to matrices since a MATLAB matrix is stored (by columns) in contiguous locations in the computer's RAM. The speed of a numerical algorithm in MATLAB is very sensitive to whether or not vectorized operations are used.

       MATLAB is a matrix language, which means it is designed for vector and matrix operations. You can often speed up your M-file code by using vectorizing algorithms that take advantage of this design. Vectorization means converting for and while loops to equivalent vector or matrix operations.

i = 0;

for t = 0:.01:1000;

    i = i+1;

    y(i) = sin(t);

end

运行时间为30.776秒。

        这段代码是很自然的从C语言的形式转化而来的,但其效率很低!Matlab是实时为变量分配内存的,在第一遍循环时(即i=1时),Matlab为y向量(长度1)分配内存。以后每执行一次循环,Matlab都会在y的末尾附加新的元素。这不仅导致分配内存的调用的增加,也使得y的各个元素在内存中的分布不是连续的(就像数据结构中数组和链表的区别相比之下,下面的代码效率提高不少:

改为向量化代码:

t = 0:.01:1000;

y = sin(t);

运行时间为0秒。

     第一个语句分配了一个连续的内存空间来存储具有多个元素的向量t。类似的,第二个语句在分配内存时,也是分配了一个连续的内存空间来存储具有多个元素的向量y。撇去计算sin的消耗不算,就内存分配命令的执行次数和对向量元素访问的方便程度来说,高下立见。

Functions Used in Vectorizing,Some of the most commonly used functions for vectorizing are:alldiffipermutepermute reshapesqueezeanyfindlogicalprodshiftdimsub2indcumsumind2subndgridrepmat sortsum

 

3加速方法2——Preallocating Arrays(预分配空间)

   You can often improve code execution time by preallocating the arrays that store output results. Preallocation makes it unnecessary for MATLAB to resize an array each time you enlarge it. Use the appropriate preallocation function for the kind of array you are working with.

Preallocation also helpsreduce memory fragmentation if you work with large matrices.

      虽然Matlab会自动调整变量的大小,我们最好还是预先为变量分配内存空间。因为这样可以使调用内存分配命令的次数降为1,也可以使变量在内存中连续存储(当变量为矩阵时是按列在内存中连续存储)而所谓“预先为变量分配内存空间” ,是指在知道变量的大小的情况下,在变量中的任何一个元素都未被引用之前,创建一个大小和其一致的变量。

For example, methods for preallocating and initializing a struct array are as follows:
To allocate memory for a0 25-by-50 struct array with fields a, b, and c and initialize the entire array to [], use either of the following two methods:
S(25,50) = struct( 'a', [], 'b', [], 'c',[]);
S(25,50).a = [];   S(25,50).b = [];   S(25,50).c = [];
After the memory has been allocated, you can begin to construct the array by assigning data to it.

例如,下面的代码自上而下,运行效率是不断提高的:

 第一段:

dx = pi/30;
nx = 1 + 2*pi/dx;
nx2 = nx/2;

for i = 1:nx2
  x(i) = (i-1)*dx;
  y(i) = sin(3*x(i));
end

for i = nx2+1:nx
  x(i) = (i-1)*dx;
  y(i) = sin(5*x(i));
end


 第二段:

dx = pi/30;
nx = 1 + 2*pi/dx;
nx2 = nx/2;

x = zeros(1,nx);      % 为向量x预分配内存
y = zeros(1,nx);      % 为向量y预分配内存

for i = 1:nx2
   x(i) = (i-1)*dx;
   y(i) = sin(3*x(i));
end

for i = nx2+1:nx
   x(i) = (i-1)*dx;
   y(i) = sin(5*x(i));
end

 第三段:

x = 0:pi/30:2*pi;     % 计算向量x的值
nx = length(x);
nx2 = nx/2;
 
y = x;                % 为向量y预分配内存
 
for i = 1:nx2
   y(i) = sin(3*x(i));
end
 
for i = nx2+1:nx
   y(i) = sin(5*x(i));
end


 第四段:

x = 0:pi/30:2*pi;                  % 计算向量x的值
nx = length(x);
nx2 = nx/2;
 
y = x;                             % 为向量y预分配内存
 
y(1:nx2) = sin(3*x(1:nx2));        % 计算y的第1部分的值
y(nx2+1:nx) = sin(5*x(nx2+1:nx));  % 计算y的第2部分的值

4其他加速方法:

Coding Loops in a MEX-File for Speed

If there are instances where you must use a for loop, consider coding the loop in a MEX-file. In this way, the loop executes much more quickly since the instructions in the loop do not have to be interpreted each time they execute.

Functions Are Faster Than Scripts

Your code will execute more quickly if it is implemented in a function rather than a script. Every time a script is used in MATLAB, it is loaded into memory and uated one line at a time. Functions, on the other hand, are compiled into pseudo-code and loaded into memory once. Therefore, additional calls to the function are faster.

Load and Save Are Faster Than File I/O Functions

If you have a choice of whether to use load and save instead of the MATLAB file I/O routines, choose the former. The load and save functions are optimized to run faster and reduce memory fragmentation.

Avoid Large Background Processes

Avoid running large processes in the background at the same time you are executing your program in MATLAB. This frees more CPU time for your MATLAB session.

5、多线程

在matlab desktop里,File->Preferences->General->Multithreading, 看是否选择了Enable Multithreaded Computation。

如果没选,check it, 看是否有提速。

6、使用逻辑运算代替find操作

find函数返回符合条件的元素的位置,然后还需要进行一系列的操作,比较费时,可以直接通过逻辑运算代替。

如:

[x, y] = find(hsv(:,:,1>0.5));

用下面的代码代替:

index = hsv(:,:,1)>0.5;

7、Correct code is always more important than speed

Vectorization sometimes makes MATLAB code hard to read. If you find yourself puzzling over the code, or more importantly if you find yourself wondering if the code performs the correct calculation, then stop trying to optimize performance.

Always remember  

    Code that gives incorrect, or inaccurate results is useless, no matter how fast it executes.


参考自:

        http://www.360doc.com/content/10/0814/22/2137281_46089200.shtml

        matlab help文件

        Improving the Speed of MATLAB Calculations

你可能感兴趣的:(matlab提速技巧)