[英]Intel Intrinsics code optimization
因此,我正在嘗試將int短整數a [101]與intel內在函數相乘。 我已經完成了加法運算,但是我似乎無法弄清楚為什么它不能與乘法一起使用。 同樣在我們使用32位整數之前,現在我們使用16位短整數,所以據我所知,我們可以在內部函數中使用兩倍多的值來填充128位?
我試圖做的天真的例子:
int main(int argc, char **argv){
short int a[101];
int len = sizeof(a)/sizeof(short);
/*Populating array a with values 1 to 101*/
mult(len, a);
return 0;
}
int mult(int len, short int *a){
int result = 0;
for(int i=0; i<len; i++){
result += a[i]*20;
}
return result;
}
我的代碼試圖在內部函數中做同樣的事情
/*Same main as before with a short int a[101] containing values 1 to 101*/
int SIMD(int len, short int *a){
int res;
int val[4];
/*Setting constant value to mulitply with*/
__m128i sum = _mm_set1_epi16(20);
__m128i s = _mm_setzero_si128( );
for(int i=0; i<len/4*4; i += 4){
__m128i vec = _mm_loadu_si128((__m128i *)(a+i));
s += _mm_mul_epu32(vec,sum);
}
_mm_storeu_si128((__m128i*) val, s);
res += val[0] + val[1] + val[2] + val[3];
/*Haldeling tail*/
for(int i=len/4*4; i<len; i++){
res += a[i];
}
return res;
}
因此,我確實得到了一個數字,但是該數字與朴素的方法不匹配,我嘗試了其他內在函數並更改數字,以查看它是否有任何顯着的區別,但是沒有什么接近我期望的輸出。 此刻的計算時間也幾乎與幼稚的時間相同。
一個__m128i
有8 short
。 所以:
for(int i=0; i<len/4*4; i += 4)
應該
for(int i=0; i<len/8*8; i += 8)`
和:
res += val[0] + val[1] + val[2] + val[3];
應該:
res += val[0] + val[1] + val[2] + val[3] + val[4] + val[5] + val[6] + val[7];
和:
for(int i=len/4*4; i<len; i++)
應該:
for(int i=len/8*8; i<len; i++)
在:
s += _mm_mul_epu32(vec,sum);
_mm_mul_epu32
在32位元素上運行。 它應該是:
s += _mm_mullo_epi16(vec, sum);
對象res
未初始化; 它應該是:
int res = 0;
這是工作代碼:
#include <stdio.h>
#include <stdlib.h>
#include <immintrin.h>
// Number of elements in an array.
#define NumberOf(x) (sizeof (x) / sizeof *(x))
// Compute the result with scalar arithmetic.
static int mult(int len, short int *a)
{
int result = 0;
for (size_t i=0; i<len; i++)
{
result += a[i]*20;
}
return result;
}
// Compute the result with SIMD arithmetic.
static int SIMD(int len, short int *a)
{
// Initialize the multiplier and the sum.
__m128i multiplier = _mm_set1_epi16(20);
__m128i s = _mm_setzero_si128( );
// Process blocks of 8 short.
for (int i=0; i<len/8*8; i += 8)
{
__m128i vec = _mm_loadu_si128((__m128i *)(a+i));
// Multtiply by multiplier and add to sum.
s = _mm_add_epi16(s, _mm_mullo_epi16(vec, multiplier));
}
// Store the sum so far so its individual elements can be manipulated.
short val[8];
_mm_storeu_si128((__m128i*) val, s);
// Add the individual elements.
int res = 0;
for (size_t i = 0; i < 8; ++i)
res += val[i];
// Add the elements in the tail.
for (size_t i = len/8*8; i < len; ++i)
{
res += a[i];
}
return res;
}
int main(int argc, char **argv)
{
short int a[96];
int len = NumberOf(a);
// Initiailize a.
for (size_t i = 0; i < len; ++i)
a[i] = i+1;
printf("sum by scalar arithmetic is %d.\n", mult(len, a));
printf("sum by SIMD arithmetic is %d.\n", SIMD(len, a));
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.