matlab运行速度对比,提高Matlab m文件的运行速度(2)
m文件的不同编程风格对程序的运行速度也有比较大的影响,下面的代码比较了采用for 循环关系运算赋值,for循环+if 语句以及直接采用数组运算的运行速度。比较的结果第三种方法采用数组直接运算最快,第一种方法次之,第二种方法最慢。第一种方法的运行速度约为第三种方法的两到三倍,第二种方法为第三种方法的三到四倍。具体在我的电脑中的一次运行结果为:0.28125秒,0.39063和0.09375。func
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=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)]);
%% to evaluate the for loop time with memory allocation first
% with if else clause
StartTime = cputime;
Res = zeros(Length, 1);
for i=1:Length
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)]);
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)