Matlab: Which is faster? Predestination of useful objects or not?

I have to do the calculations in a matrix with very large matrices. I already made sure to use matrix operations where possible, etc. Now we are trying to fine tune. So, let A, B, C and D be matrices:

C=A*B;
D=cos(C);

It seems trivial that the following will be faster (correct me if I am wrong):

D=cos(A*B)

My question is if it will be faster if there are more calls to a predefined object:

D=f1(A*B) + f2(A*B) + …;

instead of predefining C = A * B (which would save a lot of the calculations that I assume). I have a lot of such an expression, so some general understanding would be helpful (at least know which parameters depend on the size of the matrix).

+4
2

, :

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

enter image description here

+5

, , , :

D=f1(A*B) + f2(A*B) + …;

:

C = A * B;

D=f1(C) + f2(C) + …;

, . matlab, n-, .

, . .

0

Source: https://habr.com/ru/post/1619284/


All Articles