如何在C++中对循环进行矢量化

How to vectorize for loop in C++?

本文关键字:循环 矢量化 C++      更新时间:2023-10-16

我是C++的新手,所以我想知道for循环是否可以在C++中进行向量化。在Python、Matlab中,矢量化增加了性能,SIMD操作,我想知道这在C++中是否可行?如果是,怎么办?如果它很长,你能给我指一个教程吗?

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 ; 
}

我正在类矩阵中进行更复杂的循环,如果你能给我一个关于如何进行矢量化的启发,那将非常有帮助。

旁注-(我应该单独提问吗?)我将矩阵实现为1D std::向量。对于30000 X 30000(10^8)的大小,我在VS中遇到了一个调试错误。我在网上搜索,发现std::vector的限制为约5000万。如何支持较大大小的矩阵。Matlab支持大约20亿(10^9)个或更多的矢量元素。我可以用C++做什么来获得相同的大小?我应该重新使用数组并自己进行内存分配吗?

谢谢。

对于For循环的"矢量化",可以使用OpenMPhttp://openmp.org/wp/或Intel TBB。

如果你不想自己实现基本的数学函数,你可以使用像Armadillo这样的Math Libhttp://arma.sourceforge.net/.他们正在为您进行优化。