![](/img/trans.png)
[英]I have a problem with C++ because it refuses to display the answer and I don't know where the problem is in code
[英]I don't understand where I have a problem in code using sse
我是 sse 編程的新手。 我想編寫代碼,在其中對向量 v 中的 4 個連續數字求和,並將該求和的結果寫入 ans 向量中。 我想使用 sse 編寫優化的代碼。 但是當我設置大小等於 4 時,我的程序正在運行。 但是當我將大小設置為 8 時,我的程序不起作用,並且出現以下錯誤消息:“拋出異常:讀取訪問沖突。
ans 是 0x1110112。
如果有這個異常的處理程序,程序可能會安全地繼續。”我不明白我哪里有問題。我分配內存正確,我在哪個地方有問題。有人可以幫助我,我會真的很感謝。
#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;
}
您正在使用需要特殊版本的加載和存儲功能的未對齊內存。 您正確使用了_mm_loadu_pd
但_mm_store_pd
不適用於未對齊的內存,因此您應該將其更改為_mm_storeu_pd
。 還要考慮使用對齊的內存,這將導致更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.