nnrales
nnrales

Reputation: 1519

How to vectorize for loop in C++?

I am new to C++ , so I was wondering whether for loops can be vectored in C++. In Python,Matlab , vectorization adds performance, SIMD operations , I was wondering whether this was possible in C++ ? If so how ? If it is long could you point me to a tutorial ?

template <class T>
matrix<T> matrix<T>::operator*( matrix<T> &rhs)
/*
    it takes the current matrix , multiplies it by the matrix on the right , and returns 
    a new matrix 
*/
{
    matrix<T> result(_rows,rhs._cols);

    if(_cols == rhs._rows ){
                for(long long  i = 1; i <= _rows ;i++){
                    for(long long  j = 1 ; j <= rhs._cols ; j++){
                        for(long long  k = 1; k <= _cols ; k++)
                            result(i,j) += get(i,k) * rhs(k,j);// get(i,k) gives the elements in the current matrix. 

                    }   
                }
        //}else error("Cols Does Not Match");
    }else error("Rows Does Not Match");

    return result ; 
}

I am doing more complicated loops in my class matrix , if you could give me a heuristic on how to do vectorization , it would help tremendously.

Side Note- (Should I make this a separate question ?) I am implementing the matrix as a 1D std::vector. For sizes of 30000 X 30000 (10^8) , I get a debug error in VS. I searched online and found the limit of std::vector to be ~ 50 million . How can I support matrices of larger size. Matlab support about 2 billion (10^9) vector element or more. What can I do in C++ to get the same size ? Should I fall back to using arrays and do the memory allocation myself?

Thank you.

Upvotes: 0

Views: 1927

Answers (1)

kylecorver
kylecorver

Reputation: 459

For 'Vectorization' of for-loops you could use OpenMP http://openmp.org/wp/ or Intel TBB.

If you do not want to implemented basic-mathematical functions yourself you can use Math-Libs like Armadillo http://arma.sourceforge.net/. They are doing the optimization for you.

Upvotes: 1

Related Questions