MATLAB Answers

0

Why is vectorization faster than the parallel computing?

Asked by wei zhang on 4 Sep 2019
Latest activity Commented on by Adam
on 4 Sep 2019
Accepted Answer by Jan
I am trying to speed my code, which processing some big geometry surface. From scanning on the website, I found 2 way to optimize my code. One is vectorization, the other is using parallel computing toolbox. My computer has 16 cores, but with relative low speed, 2.0 ghz. As my experience, I found vectorization is always faster than parallel computing. I just wonder the reason about it. Does Matlab build-in function could do the vectorization on many "virtual small processors", which is much more than the computer cores? Like GPU or something else? I want to know a little about the machinism under it.
Thank you very much for any hints and explainations.

  2 Comments

The more specific a question is, the easier is an answer. If you post some code, it is possible to explain, what happens. Asking aboput the general mechanism demands for an exhaustive answer, which will most likely do not match your point.
Vectorisation takes advantage of the fact that the same (usually fairly simple, at a component level) operation is being performed on many elements of the array, which it can process very efficiently at the low-level.
Parallelisation has data copying overheads and many other considerations, as discussed by Jan in his answer below.
Where vectorisation is possibly it is usually preferable (faster) to parallelisation.

Sign in to comment.

Products


Release

R2019a

1 Answer

Answer by Jan
on 4 Sep 2019
 Accepted Answer

It depends on the problem. Parallelization is not trivial. If you use e.g. 16 cores and write the results in neighboring elements of a UINT8 vector, you get a collision in the cache-line. As result the total computing time can exceed the time of a serial code, because the threads are waiting for eachother. Such collisions can occur in other resources also, e.g. if the memory is exhausted and expensive disk caching is used, or if data are requested through a network.
Many Matlab functions are mutli-threaded, e.g. sum: For large inputs Matlab computes the sum in several parts using different threads. For a 1e5 x 1e5 matrix all cores are used (most likely). Computing this by parallelization in a parfor loop is less efficient, because there is some overhead for starting the threads. The multi-threaded functions are written such, that resource collisions are avoided (at least in most cases. In some cases, e.g. logical indexing or cell2mat there is some potential for improvements).
So before you start to parallelize a function, check if it uses many cores already in the sequential version. Then starting mutliple threads of a parpool on a single machine will not improve the efficiency.

  0 Comments

Sign in to comment.