我必须在matlab中用非常大的矩阵进行计算。我已经确保在可能的情况下使用矩阵运算等,现在正在尝试微调。因此,设A,B,C和D为矩阵:
C=A*B;
D=cos(C);
以下内容可能会更快(如果我错了,请纠正我),这似乎微不足道:
D=cos(A*B)
我的问题是,如果有更多的对预定义对象的调用,那么这样做会更快:
D=f1(A*B) + f2(A*B) + …;
而不是预先定义C=A*B (这将节省大量的计算费用)。我有很多这样的表达式,所以一些一般性的洞察力是有用的(至少知道它取决于什么类型的参数,即矩阵大小)。
发布于 2015-12-10 02:51:54
从经验来看,我知道变化:
y = f1(A*B) + f2(A*B)...
至
C = A*B;
y = f1(C) + f2(C)...
当您有优化代码的场景时--中间变量"C“上的操作按上面所示多次完成时,速度会更快。
当操作只完成一次时,它不太可能产生性能改进或退化,就像我认为在变量被传递到函数之前由Matlab内联完成的操作。
为了帮助演示这一点,您可以看到下面的基准函数,它测试变量A& B上的单个和多个操作(3)。
底部的图显示了结果,与上面的点是一致的。
function benchmark
% test array
testArray = 100:100:5000; % 5000 will take quite a while - to test start with smaller (e.g. 500)
% preallocate
sep=zeros(numel(testArray),1);
inline=sep;
sepcombined = sep;
inlinecombined = sep;
fcnSep1 = @() sepfcn;
fcnInline1 = @() inlinefcn;
fcnSep2 = @() sepfcn2;
fcnInline2 = @() inlinefcn2;
% set up array counter
count = 1;
% run throuh all tests
for i=testArray
% create A&B
A = zeros(i,i)+2;
B = A+1;
% run single actions
sep(count) = timeit (fcnSep1);
inline(count) = timeit (fcnInline1);
% combined actions
sepcombined(count) = timeit (fcnSep2);
inlinecombined(count) = timeit (fcnInline2);
% increment the counter
count = count + 1;
% monitor progress
disp ( i );
end
% use nested functions for the actions
function sepfcn
C = A*B;
sum(C);
end
function inlinefcn
sum(A*B);
end
function sepfcn2
C = A*B;
sum(C)+max(C)+min(C);
end
function inlinefcn2
sum(A*B)+max(A*B)+min(A*B);
end
%% plot the results
figure;
subplot ( 2, 1, 1 );
plot ( testArray, sep, 'r-', testArray, inline,'b-' );
legend ( 'sep', 'inline' )
title ( 'single action' );
ylabel ( 'time (s)' )
xlabel ( 'matrix size' )
subplot ( 2, 1, 2 );
plot ( testArray, sepcombined, 'r-', testArray, inlinecombined,'b-' );
legend ( 'sep', 'inline' )
title ( 'multiple actions' );
xlabel ( 'matrix size' )
ylabel ( 'time (s)' )
end
发布于 2015-12-09 16:49:16
是的,您可以通过从以下语句中更改代码来加快速度:
D=f1(A*B) + f2(A*B) + …;
这样的声明:
C = A * B;
D=f1(C) + f2(C) + …;
因为很明显,执行的乘法较少。我见过很多matlab代码重复表达式,因为作者只是在复制-n粘贴。
至少,需要维护和调试的表达式将减少。所以一般不要重复你自己。
https://stackoverflow.com/questions/34191486
复制