SSE小试牛刀(一)

1.介绍

    SSE绝对是优化神器之一,是由英特尔所提出的cpu指令集,具有Intel SSE指令集支持的处理器有8个128位的寄存器,每一个寄存器可以存放4个(32位)单精度的浮点数,SSE的英文全称:Stream SIMD Extentions,而SIMD的英文全称:Single Instruction Multiple Data。它的强悍地方在于,一道指令可以完成多个(一般是4个)数据的操作

    下面主要介绍一下,浮点型算术指令,其它的都类似,可以查看说明书://download.csdn.net/download/u013289254/11459202

    SSE的指令格式:

           第一部分为指令的操作,可选择项比较多,比如add,sub

           第二部分为p或者s,分别表示为packed(多个一起运算)或者scala(第一个运算)r;

           第三部分为s,表示单精度浮点数

2.代码

#include <iostream>
#include <windows.h>
#include <xmmintrin.h>

using namespace std;

void sse_mul(float *srcOne, float *srcTwo, float *dest, int size)
{
	int n = size >> 2;
	for (int i = 0; i < n; ++i)
	{
		*(__m128*)(dest + i * 4) = _mm_mul_ps(*(__m128*)(srcOne + i * 4), *(__m128*)(srcTwo + i * 4));
	}
}

void normal_mul(float *srcOne, float *srcTwo, float *dest, int size)
{
	for (int i = 0; i < size; ++i)
	{
		dest[i] = srcOne[i] * srcTwo[i];
	}
}

int main()
{
	int timeStart = 0, timeEnd = 0;
	const int size = 10000;

	_MM_ALIGN16 float *srcOne = (_MM_ALIGN16 float*)_mm_malloc(sizeof(float)*size, 16);
	_MM_ALIGN16 float *srcTwo = (_MM_ALIGN16 float*)_mm_malloc(sizeof(float)*size, 16);
	_MM_ALIGN16 float *dest = (_MM_ALIGN16 float*)_mm_malloc(sizeof(float)*size, 16);

	for (int i = 0; i < size; ++i){
		srcOne[i] = (float)i;
		srcTwo[i] = size - (float)i;
	}

	// for循环乘法
	timeStart = GetTickCount();
	for (int i = 0; i < size; ++i) {
		normal_mul(srcOne, srcTwo, dest, size);
	}
	timeEnd = GetTickCount();
	cout << "normal_mul test time is " << (timeEnd - timeStart) * 0.001 << endl;

	// SSE指令乘法
	timeStart = GetTickCount();
	for (int i = 0; i < size; ++i) {
		sse_mul(srcOne, srcTwo, dest, size);
	}
	timeEnd = GetTickCount();
	cout << "sse_mul test time is " << (timeEnd - timeStart) * 0.001 << endl;

	// 释放内存
	_mm_free(srcOne);
	_mm_free(srcTwo);
	_mm_free(dest);

	system("pause");
	return 0;
}

    效果还是不错的,见下面图片:

发布了138 篇原创文章 · 获赞 141 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u013289254/article/details/104563583