回答

收藏

提高m文件的运行速度(2)

无线通信 无线通信 2762 人阅读 | 0 人回复 | 2007-11-03

m文件的不同编程风格对程序的运行速度也有比较大的影响,下面的代码比较了采用for 循环关系运算赋值,for循环+if 语句以及直接采用数组运算的运行速度。比较的结果第三种方法采用数组直接运算最快,第一种方法次之,第二种方法最慢。第一种方法的运行速度约为第三种方法的两到三倍,第二种方法为第三种方法的三到四倍。

具体在我的电脑中的一次运行结果为:0.28125秒,0.39063和0.09375。

function PerformanceComp()
Length = 10^7;
Source = round(rand(Length, 1)) * 2 - 1;

%% to evaluate the for loop time with memory allocation first
StartTime = cputime;
Res = zeros(Length, 1);
for i=1ength
??? Res(i) = Source(i) >= 0;
end
EndTime = cputime;
Duration = EndTime - StartTime;
disp(['The for loop with memory allocation running time is ' num2str(Duration)]);
%% to evaluate the for loop time with memory allocation first
%? with if else clause
StartTime = cputime;
Res = zeros(Length, 1);
for i=1ength
??? if Source(i) >= 0
??????? Res(i) = 1;
??? else
??????? Res(i) = 0;
??? end
end
EndTime = cputime;
Duration = EndTime - StartTime;
disp(['The for loop with memory allocation running time' ...
??? 'with if clause is ' num2str(Duration)]);
%% to evaluate the array operation running time
StartTime = cputime;
Res = Source >= 0;
EndTime = cputime;
Duration = EndTime - StartTime;
disp(['The array operation time is ' num2str(Duration)]);
分享到:
回复

使用道具 举报

您需要登录后才可以回帖 注册/登录

本版积分规则

关闭

站长推荐上一条 /3 下一条