I was reading a book about Matlab ("Accelerating Matlab with GPU computing - A Primer with Examples" by Jung Suh and Youngming Kim, 2013. Chapter 1.7 Examples).

I read an example where it said that:

by using elemental calculation, matrix calculation, and function call instead of for loops, the speed can be dramatically accelerated.

In the case I read, it reduced calculation time from 50s to 0.5s.

My questions:

  1. which syntax is more "resources saving" and "faster": function call, for, while, if, switch, and (i.e. search elements in a matrix or set) etc.?

  2. How fast is the element-wise calculation, addition, and matrix calculation etc.?

For the convince of understanding, a short example was given below:

%%% First case
B = 0;
A = 1:1e8;
for i=1:1000
    B = B + A(i);

%%% Second case
B = 0;
A = 1:1e8;
B = sum(A);

%%% Third case
C = ones(1e8,1);
B = 0;
A = 1:1e8;
B = A*C;

with the following timing results

Elapsed time is 0.463159 seconds.

Elapsed time is 0.501524 seconds.

Elapsed time is 0.532470 seconds.

In the above example, all three methods had different but comparable speed.

  • $\begingroup$ Can you provide the information about the book you are reading? $\endgroup$ – nicoguaro Jun 13 '18 at 15:51
  • $\begingroup$ I think that you are referring to vectorization of operations, am I right? $\endgroup$ – nicoguaro Jun 13 '18 at 16:46
  • $\begingroup$ @nicoguaro Some of this is also down to the generic optimisation differences between compiled and interpreted code. $\endgroup$ – origimbo Jun 13 '18 at 16:56
  • 3
    $\begingroup$ I still think it is too broad, since the answer will be very different depending on what you try to compute. It also very much depends on the version of Matlab (and, to a degree, the hardware and operating system since matrix operations are punted to the Intel MKL library); as you notice, simple(!) for loops have become much faster in recent versions of Matlab compared to a few years ago. $\endgroup$ – Christian Clason Jun 14 '18 at 7:14
  • 1
    $\begingroup$ Instead of trying to think of it in terms of which Matlab syntax is faster, which I think is a bit of a dead end, try thinking more concretely in terms of what actually gets executed on the CPU: is it running a (slow, non-JIT) interpreter over your code, or is execution dispatched to a compiled optimized function. Trying to classify different aspects of Matlab's syntax as fast or slow wouldn't get at the underlying issues and wouldn't help understand. $\endgroup$ – Kirill Jun 16 '18 at 15:37