Any way to vectorize in C

My question may seem primitive or dumb because I just switched to C. I have been working with MATLAB for several years and I learned that any calculations must be vectorized in MATLAB and I must avoid any loop for

to get acceptable performance ... It looks like if I want to add two vectors, or multiply matrices, or do any other matrix computation, I have to use a loop for

. Understandable if you let me know if there is a way to do the calculations in a vectorized sense, eg. reading all the elements of a vector using just one command and adding those elements to another vector using one command. Thanks to

+3


source to share


3 answers


MATLAB suggests that you avoid for looping for

because most of the operations available for vectors and matrices are already implemented in its API and are ready to use. They are probably optimized and they work directly on the underlying data, not at the MATLAB language level, I think this is an opaque implementation.

Even MATLAB uses loops to do most of its magic (or delegates them to highly specialized assembly instructions or via CUDA to the GPU).



What you are asking is not directly possible, you would need to use loops to work with vectors and matrices, in fact you would be looking for a library that allows you to do most of the work without using the for loop directly, but using the already defined functions that they are wrapped.

+3


source


There is no way in C to perform operations in a vectorized way. You can use structures and functions to abstract away the details of the operations, but in the end you will always use fors to process your data.



As far as the speed of C is concerned, it is a compiled language and you don't get the benefit of using it for loops on CC has the advantage (over MATLAB) that it hides nothing from you, so you can always see where your time is being used. On the other hand, you'll notice that things that MATLAB makes trivial (svd, cholesky, inv, cond, imread, etc.) are Complicated in C.

+1


source


As mentioned, it is not possible to hide for loops. However, I doubt the MATLAB code produces faster than the one generated by C. If you compile your C code with -O3

, it will try to use every hardware feature available to your computer, such as SIMD extensions and a few questions ... Moreover, if your code is good and it doesn't call too many pipelines, and you are using the cache, it will be very fast. But I think you are looking for some libraries, google search for LAPACK or BLAS, they might be what you are looking for.

+1


source







All Articles