这种观察并不重要,因为浪费在循环语句上的时间性能可能远高于循环本身.但无论如何,我会分享它,因为我搜索并找不到关于此的话题.我总是有这样的印象:预先分配我将循环的数组,然后循环它,将比直接循环它更好,并决定检查它.代码将比较这两个fors之间的效率:
disp('Pure for with column on statement:')
tic
for k=1:N
end
toc
disp('Pure for with column declared before statement:')
tic
m=1:N;
for k=m
end
toc
但我得到的结果是:
Pure for with column on statement:
Elapsed time is 0.003309 seconds.
Pure for with column declared before statement:
Elapsed time is 0.208744 seconds.
为什么会这样?不应该预先分配更快?
事实上,matlab帮助说:
Long loops are more memory efficient when the colon expression appears
in the FOR statement since the index vector is never created.
因此,与我的期望相反,for语句中的列表达式更好,因为它不分配向量,因此更快.
我做了以下脚本来测试其他场合我也认为会更快:
% For comparison:
N=1000000;
disp('Pure for loop on cell declared on statement:')
tic
for k=repmat({1},1,N)
end
toc
disp('Pure for loop on cell declared before statement:')
tic
mcell=repmat({1},1,N);
for k=mcell
end
toc
disp('Pure for loop calculating length on statement:')
tic
for k=1:length(mcell)
end
toc
disp('Pure for loop calculating length before statement:')
tic
lMcell = length(mcell);
for k=1:lMcell
end
toc
disp('Pure while loop using le:')
% While comparison:
tic
k=1;
while (k<=N)
k=k+1;
end
toc
disp('Pure while loop using lt+1:')
% While comparison:
tic
k=1;
while (k
k=k+1;
end
toc
disp('Pure while loop using lt+1 pre allocated:')
tic
k=1;
myComp = N+1;
while (k
k=k+1;
end
toc
时间是:
Pure for loop on cell declared on statement:
Elapsed time is 0.259250 seconds.
Pure for loop on cell declared before statement:
Elapsed time is 0.260368 seconds.
Pure for loop calculating length on statement:
Elapsed time is 0.012132 seconds.
Pure for loop calculating length before statement:
Elapsed time is 0.003027 seconds.
Pure while loop using le:
Elapsed time is 0.005679 seconds.
Pure while loop using lt+1:
Elapsed time is 0.006433 seconds.
Pure while loop using lt+1 pre allocated:
Elapsed time is 0.005664 seconds.
结论:
>只需通过逗号语句循环就可以获得一些性能,但与for循环所花费的时间相比,这可以忽略不计.
>对于细胞,差异似乎可以忽略不计.
>最好在进行循环之前预先分配长度.
>虽然没有预先分配向量,但是while具有与for相同的效率,这如前所述是有意义的
>正如预期的那样,最好在while语句之前计算固定表达式.
但我无法回答的问题是,细胞怎么样,为什么没有时间差异?开销可能远低于观察到的开销?或者它必须分配单元格,因为它不是一个基本类型的双重?
如果您知道有关此主题的其他技巧,请填写.
只需添加时间来显示转动功能的结果(‘accel’,’off’),如@Magla的回答所述.
Pure for with column on statement:
Elapsed time is 0.181592 seconds.
Pure for with column declared before statement:
Elapsed time is 0.180011 seconds.
Pure for loop on cell declared on statement:
Elapsed time is 0.242995 seconds.
Pure for loop on cell declared before statement:
Elapsed time is 0.228705 seconds.
Pure for loop calculating length on statement:
Elapsed time is 0.178931 seconds.
Pure for loop calculating length before statement:
Elapsed time is 0.178486 seconds.
Pure while loop using le:
Elapsed time is 1.138081 seconds.
Pure while loop using lt+1:
Elapsed time is 1.241420 seconds.
Pure while loop using lt+1 pre allocated:
Elapsed time is 1.162546 seconds.
结果现在按预期区域……