如何使用gcc编译SIMD代码

8
我为SIMD编写了矩阵乘法代码,我能够在Visual Studio中编译它,但现在我需要使用gcc/g++在Ubuntu中编译它。 我应该使用哪些命令来编译它? 我需要更改代码本身吗?
#include <stdio.h>
#include <stdlib.h>
#include <xmmintrin.h>
#include <iostream>
#include <conio.h>
#include <math.h>
#include <ctime>

using namespace std;

#define MAX_NUM 1000
#define MAX_DIM 252

int main()
{
    int l = MAX_DIM, m = MAX_DIM, n = MAX_DIM;
    __declspec(align(16)) float a[MAX_DIM][MAX_DIM], b[MAX_DIM][MAX_DIM],c[MAX_DIM][MAX_DIM],d[MAX_DIM][MAX_DIM];

    srand((unsigned)time(0));

    for(int i = 0; i < l; ++i)
    {
        for(int j = 0; j < m; ++j)
        {
            a[i][j] = rand()%MAX_NUM;
        }
    }

    for(int i = 0; i < m; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            b[i][j] = rand()%MAX_NUM;
        }
    }

    clock_t Time1 = clock();

    for(int i = 0; i < m; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            d[i][j] = b[j][i];
        }
    }

    for(int i = 0; i < l; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            __m128 *m3 = (__m128*)a[i];
            __m128 *m4 = (__m128*)d[j];
            float* res;
            c[i][j] = 0;
            for(int k = 0; k < m; k += 4)
            {
                __m128 m5 = _mm_mul_ps(*m3,*m4);
                res = (float*)&m5;
                c[i][j] += res[0]+res[1]+res[2]+res[3];
                m3++;
                m4++;
            }
        }
        //cout<<endl;
    }

    clock_t Time2 = clock();
    double TotalTime = ((double)Time2 - (double)Time1)/CLOCKS_PER_SEC;
    cout<<"Time taken by SIMD implmentation is "<<TotalTime<<"s\n";

    Time1 = clock();

    for(int i = 0; i < l; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            c[i][j] = 0;
            for(int k = 0; k < m; k += 4)
            {
                c[i][j] += a[i][k] * b[k][j];
                c[i][j] += a[i][k+1] * b[k+1][j];
                c[i][j] += a[i][k+2] * b[k+2][j];
                c[i][j] += a[i][k+3] * b[k+3][j];

            }
        }
    }

    Time2 = clock();
    TotalTime = ((double)Time2 - (double)Time1)/CLOCKS_PER_SEC;
    cout<<"Time taken by normal implmentation is "<<TotalTime<<"s\n";

    getch();
    return 0;
}

我的问题是如何在Ubuntu上使用g++或gcc编译器编译此代码...我已经成功地在Windows中使用Visual Studio进行了编译,但不知道如何在Ubuntu中进行编译。 - abhinav
1个回答

12

你需要启用SSE,例如:

$ g++ -msse3 -O3 -Wall -lrt foo.cpp -o foo

你还需要改变:

declspec(align(16))

将其从仅限于Windows的版本更改为更具可移植性的版本:

__attribute__ ((aligned(16)))

它会给出很多这样的错误// matrix_simd.cpp:25: error: ‘a’在此范围内未声明。 - abhinav
但它已经成功编译了,我能够在Windows的Visual Studio中运行。现在我在这里遇到了这些错误,我需要添加任何头文件吗? - abhinav
谢谢,它已经编译了,但是它会给出一个警告 /// 警告:'align'属性指令被忽略 - abhinav
我曾经发誓GCC也允许declspec语法,但此刻我在移动设备上无法尝试...请参阅C++11中的'alignas'关键字。 - Nemo
@Nemo:你可能是对的,至少对于某些版本的gcc来说是这样的——我现在也在移动设备上,无法立即检查——但我知道英特尔的ICC编译器都支持。 - Paul R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接