根据我的经验,我知道改变以下内容:
y = f1(A*B) + f2(A*B)...
为了
C = A*B;
y = f1(C) + f2(C)...
在优化代码的场景下,当针对中间变量“C”的操作被多次执行时,使用这种方式会更快。如果只执行一次操作,则不太可能产生性能改进或退化,因为我认为Matlab会在将变量传递到函数之前内联执行该操作。
为了证明这一点,您可以查看下面的基准函数,该函数测试变量A和B上的单个和多个操作(3次)。
底部的图表显示了结果,与上述观点相符。
function benchmark
testArray = 100:100:5000;
sep=zeros(numel(testArray),1);
inline=sep;
sepcombined = sep;
inlinecombined = sep;
fcnSep1 = @() sepfcn;
fcnInline1 = @() inlinefcn;
fcnSep2 = @() sepfcn2;
fcnInline2 = @() inlinefcn2;
count = 1;
for i=testArray
A = zeros(i,i)+2;
B = A+1;
sep(count) = timeit (fcnSep1);
inline(count) = timeit (fcnInline1);
sepcombined(count) = timeit (fcnSep2);
inlinecombined(count) = timeit (fcnInline2);
count = count + 1;
disp ( i );
end
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
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
![enter image description here](https://istack.dev59.com/r49kr.webp)
D=cos(A*B)
比C = A * B; D = cos(C)
快得多?我不明白。 - Matthew Gunn