, :
y = f1(A*B) + f2(A*B)...
to
C = A*B;
y = f1(C) + f2(C)...
, , , - "C" , .
, , , Matlab .
, , , (3) A B.
,
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
