简体   繁体   中英

I don't understand where I have a problem in code using sse

I am new with sse programming. I want to write code in which I sum up 4 consecutive numbers from vector v and write the result of this sum in ans vector. I want to write optimized code using sse. But when I set up size is equal to 4 my program is working. But when I set up size is 8 my program doesn't work and I have this error message: "Exception thrown: read access violation.

ans was 0x1110112.

If there is a handler for this exception, the program may be safely continued." I don't understand where I have a problem. I allocate the memory right, in which place I have a problem. Could somebody help me, I will be really grateful.

#include <iostream>
#include <immintrin.h>
#include <pmmintrin.h>
#include <vector>
#include <math.h>  
using namespace std;
arith_t = double
void init(arith_t *&v, size_t size) {
    for (int i = 0; i < size; ++i) {
        v[i] = i / 10.0;
    }
}
//accumulate with sse
void sub_func_sse(arith_t *v, size_t size, int start_idx, arith_t *ans, size_t start_idx_ans) {
    __m128d first_part = _mm_loadu_pd(v + start_idx);
    __m128d second_part = _mm_loadu_pd(v + start_idx + 2);

    __m128d sum = _mm_add_pd(first_part, second_part);
    sum = _mm_hadd_pd(sum, sum);
    _mm_store_pd(ans + start_idx_ans, sum);
}
int main() {
    const size_t size = 8;
    arith_t *v = new arith_t[size];
    arith_t *ans_sse = new arith_t[size / 4];
    init(v, size);
    init(ans_sse, size / 4);
    int num_repeat = 1;
    arith_t total_time_sse = 0;
    for (int p = 0; p < num_repeat; ++p) {
        for (int idx = 0, ans_idx = 0; idx < size; idx += 4, ans_idx++) {
            sub_func_sse(v, size, idx, ans_sse, ans_idx);
        }
    }

    for (size_t i = 0; i < size / 4; ++i) {
        cout << *(ans_sse + i) << endl;
    }
    delete[] ans_sse;
    delete[] v;
}

You're using unaligned memory which requires special versions of load and store functions. You correctly used _mm_loadu_pd but the _mm_store_pd isn't appropriate for working with unaligned memory so you should change it to _mm_storeu_pd . Also consider using aligned memory which will result in better performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM