1

組み込み関数を使用して並列化を実現する方法があることを知りました。次のコードを見つけて、それを実行したかったのですが、かなり理解できました。演算を単精度にしようとしていましたが、どうすればそれを行うことができますか?

#include <stdio.h>
#include <stdlib.h>
#include <xmmintrin.h>

inline double pi_4 (int n){
        int i;
        __m128d mypart2,x2, b, c, one;
        double *x = (double *)malloc(n*sizeof(double));
        double *mypart = (double *)malloc(n*sizeof(double));
        double sum = 0.0;
        double dx = 1.0/n;
        double x1[2] __attribute__((aligned(16)));
        one = _mm_set_pd1(1.0); // set one to (1,1)
        for (i = 0; i < n; i++){
                x[i] = dx/2 + dx*i;
        }
        for (i = 0; i < n; i+=2){
                x1[0]=x[i]; x1[1]=x[i+1];
                x2 = _mm_load_pd(x1);
                b = _mm_mul_pd(x2,x2);
                c = _mm_add_pd(b,one);
                mypart2 = _mm_div_pd(one,c); 
                _mm_store_pd(&mypart[i], mypart2);
        }
        for (i = 0; i < n; i++)
                sum += mypart[i];       
        return sum*dx;
}

int main(){
        double res;
        res=pi_4(128);
        printf("pi = %lf\n", 4*res);
        return 0;
}

double から float にすべてを変更し、たとえば、_mm_set_pd1 -> _mm_set_ps1 の代わりに正しい組み込み関数を呼び出すことを考えていました。これでプログラムが倍精度から単精度になるかどうかはわかりません。

アップデート

次のように試しましたが、セグメンテーション違反が発生しています

#include <stdio.h>
#include <stdlib.h>
#include <xmmintrin.h>

inline float pi_4 (int n){
        int i;
        __m128 mypart2,x2, b, c, one;
        float *x = (float *)malloc(n*sizeof(float));
        float *mypart = (float*)malloc(n*sizeof(float));
        float sum = 0.0;
        float dx = 1.0/n;
        float x1[2] __attribute__((aligned(16)));
        one = _mm_set_ps1(1.0); // set one to (1,1)
        for (i = 0; i < n; i++){
                x[i] = dx/2 + dx*i;
        }
        for (i = 0; i < n; i+=2){
                x1[0]=x[i]; x1[1]=x[i+1];
                x2 = _mm_load_ps(x1);
                b = _mm_mul_ps(x2,x2);
                c = _mm_add_ps(b,one);
                mypart2 = _mm_div_ps(one,c); 
                _mm_store_ps(&mypart[i], mypart2);
        }
        for (i = 0; i < n; i++)
                sum += mypart[i];       
        return sum*dx;
}
int main(){
        float res;
        res=pi_4(128);
        printf("pi = %lf\n", 4*res);
        return 0;
}
4

1 に答える 1