【发布时间】:2013-08-30 10:19:05
【问题描述】:
我用的是vs2012,想测试一下SSE和AVX的效率。 SSE 和 AVX 的代码几乎一样, 除了 SSE 使用 _m128 而 AVX 使用 _m256。 我希望 AVX 代码比 SSE 代码快两倍, 但是测试结果显示它们的速度几乎是一样的。
我尝试选择 /arch:AVX 或 /arch:SSE 或 /NOT SET 并注释 SSE 代码或注释 AVX 代码, 无论我测试什么, 用于 SSE 代码的时间约为 2138 毫秒,而 AVX 代码约为 2106 毫秒。 外层for循环只是用来增加循环时间,
#include "testfun.h"
#include <iostream>
#include <time.h>
#include <malloc.h>
#include "immintrin.h"
using namespace std;
#define dataLen 800000
void testfun()
{
float *buf1 = reinterpret_cast<float*>(_aligned_malloc( sizeof(float)*dataLen, 32 ));
float *buf2 = reinterpret_cast<float*>(_aligned_malloc( sizeof(float)*dataLen, 32 ));
for(int i=0; i<dataLen; i++)
{
buf1[i] = 1;
buf2[i] = 1;
}
double timePassed;
int t = clock();
float sum = 0;
//=========================SSE CODE=====================================
__m128 *p1 = (__m128 *)buf1;
__m128 *p2 = (__m128 *)buf2;
__m128 _result = _mm_set_ps1(0.0f);
for(int j=0;j<10000; j++)
{
p1 = (__m128 *)buf1;
p2 = (__m128 *)buf2;
_result = _mm_sub_ps(_mm_set_ps(j,0,0,0) ,_result);
for(int i=0; i<dataLen/4; i++)
{
_result = _mm_add_ps(_mm_mul_ps(*p1, *p2), _result);
p1++;
p2++;
}
}
sum = _result.m128_f32[0]+_result.m128_f32[1]+_result.m128_f32[2]+_result.m128_f32[3];
timePassed = clock() - t;
std::cout<<std::fixed<<"SSE calculate result : "<<sum<<std::endl;
std::cout<<"SSE time used: "<<timePassed<<"ms"<<std::endl;
//=========================AVX CODE=====================================
t = clock();
__m256 *pp1 ;
__m256 *pp2 ;
__m256 _rresult = _mm256_setzero_ps();
sum = 0;
for(int j=0;j<10000; j++)
{
pp1 = (__m256*) buf1;
pp2 = (__m256*) buf2;
_rresult = _mm256_sub_ps(_mm256_set_ps(j,0,0,0,0,0,0,0), _rresult);
for(int i=0; i<dataLen/8; i++)
{
_rresult = _mm256_add_ps(_mm256_mul_ps(*pp1, *pp2), _rresult);
pp1++;
pp2++;
}
}
sum = _rresult.m256_f32[0]+_rresult.m256_f32[1]+_rresult.m256_f32[2]+_rresult.m256_f32[3]+_rresult.m256_f32[4]+_rresult.m256_f32[5]+_rresult.m256_f32[6]+_rresult.m256_f32[7];
timePassed = clock() - t;
std::cout<<std::fixed<<"AVX calculate result : "<<sum<<std::endl;
std::cout<<"AVX time used: "<<timePassed<<"ms"<<std::endl;
_aligned_free(buf1);
_aligned_free(buf2);
}
【问题讨论】:
标签: c++ performance visual-studio-2012 sse avx