在进行大规模数组或者矩阵运算的时候,最好事先对其初始化,这样可以大大提高m文件的运行速度。原因在于在运行m文件的时候,Matlab逐条命令解析执行的。在执行每条命令的时候,如果遇到新的变量或者发现原来的变量大小发生变化的时候,则会开辟一块内存。在运行较大规模数组或者矩阵运算的时候,开辟内存会占用大部分时间。 试运行一下一下代码,你将会发现两种方法的运行时间有非常大的差别。没有初始化数组的运行时间为6.2969秒, 而初始化内存之后的运行时间仅仅为0.03125秒。
function PerformanceComp()
Length = 10^5;
Source = round(rand(Length, 1)) * 2 - 1;
%% to evaluate the for loop running time
StartTime = cputime;
for i=1:Length
Res(i) = Source(i) >= 0;
end
EndTime = cputime;
Duration = EndTime - StartTime;
disp(['The for loop time is ' num2str(Duration)]);
%% to evaluate the for loop time with memory allocation first
StartTime = cputime;
Res = zeros(Length, 1);
for i=1:Length
Res(i) = Source(i) >= 0;
end
EndTime = cputime;
Duration = EndTime - StartTime;
disp(['The for loop with memory allocation running time is ' num2str(Duration)]);