Wol*_*ger 4 matlab runtime matrix
我必须用非常大的矩阵在matlab中进行计算.我已经确保在可能的情况下使用矩阵运算等.现在尝试微调.所以让A,B,C和D为矩阵:
C=A*B;
D=cos(C);
Run Code Online (Sandbox Code Playgroud)
看起来微不足道,以下会更快(如果我错了,请纠正我):
D=cos(A*B)
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果有更多的预定义对象调用,它会更快吗?
D=f1(A*B) + f2(A*B) + …;
Run Code Online (Sandbox Code Playgroud)
而不是预定义C = A*B(这将节省我假设的大量计算).我有很多这样的表达方式,所以一些一般的见解是有用的(至少知道什么样的参数,即它所依赖的矩阵大小).
根据经验我知道改变:
y = f1(A*B) + f2(A*B)...
Run Code Online (Sandbox Code Playgroud)
至
C = A*B;
y = f1(C) + f2(C)...
Run Code Online (Sandbox Code Playgroud)
当你有优化代码的场景时,它会更快 - 如上所述,对中间变量"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
Run Code Online (Sandbox Code Playgroud)