前言背景一、AVX二、demo
1. 正常相加2. _mm256_add_pd 三、结论
前言
计算引擎像Spark、Presto这种,想要进一步提升算子性能,可以从算子实现方式着手。
本文简单介绍一下SIMD代表指令集 - AVX极其简单使用demo。
先贴一些基础:
SIMD:参考 https://zhuanlan.zhihu.com/p/31271788
内存对齐:参考 https://zhuanlan.zhihu.com/p/30007037
一般参考官方文档来做开发:Intel Intrinsic Guide
举例:
将两个浮点数组(vector)依次对相同位置做加法
内存对齐
取出处理完的数据
单线程,分别做100亿次运算,耗时取平均。
1. 正常相加#include#include #include #include using namespace std; class origin { long getCurrentTime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } int main() { double a[4] = {1.0, 2.0, 3.0, 4.0}; double b[4] = {10.0, 20.0, 30.0, 40.0}; double c[4] = {}; long start = getCurrentTime(); cout << "Milliseconds:(start) " << start << endl; long i = 1000000000; while (i--) { double a[] = {rand() % 100 + 13.0, rand() % 100 + 14.0, rand() % 100 + 15.0, rand() % 100 + 16.0}; double b[] = {rand() % 100 + 13.0, rand() % 100 + 14.0, rand() % 100 + 15.0, rand() % 100 + 16.0}; a[0] + b[0]; a[1] + b[1]; a[2] + b[2]; a[3] + b[3]; } long end = getCurrentTime(); cout << "Milliseconds:(end) " << getCurrentTime() << endl; cout << "Milliseconds:(cost) " << end - start << endl; for (int j = 0; j < 4; j++) { c[j] = a[j] + b[j]; } printf("%lf", c[0]); printf("%lf", c[1]); printf("%lf", c[2]); printf("%lf", c[3]); return 0; } };
结果:
Milliseconds:(start) 1647348556855 Milliseconds:(end) 1647348611330 Milliseconds:(cost) 944752. _mm256_add_pd
#include#include #include #include #include using namespace std; class intrinsic { long getCurrentTime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } int main() { double a[4] = {1.0, 2.0, 3.0, 4.0}; double b[4] = {10.0, 20.0, 30.0, 40.0}; double c[] = {}; __m256d rv; long start = getCurrentTime(); cout << "Milliseconds:(start) " << start << endl; long i = 1000000000; while (i--) { double a[] = {rand() % 100 + 13.0, rand() % 100 + 14.0, rand() % 100 + 15.0, rand() % 100 + 16.0}; double b[] = {rand() % 100 + 13.0, rand() % 100 + 14.0, rand() % 100 + 15.0, rand() % 100 + 16.0}; __m256d av = _mm256_load_pd(a); __m256d bv = _mm256_load_pd(b); _mm256_add_pd(av, bv); _mm256_hsub_pd(av, bv); _mm256_mul_pd(av, bv); _mm256_div_pd(av, bv); } long end = getCurrentTime(); cout << "Milliseconds:(end) " << getCurrentTime() << endl; cout << "Milliseconds:(cost) " << end - start << endl; __m256d av = _mm256_load_pd(a); __m256d bv = _mm256_load_pd(b); rv = _mm256_add_pd(av, bv); _mm256_storeu_pd(c, rv); printf("%lf", c[0]); printf("%lf", c[1]); printf("%lf", c[2]); printf("%lf", c[3]); return 0; } };
结果:
Milliseconds:(start) 1647349685912 Milliseconds:(end) 1647349723570 Milliseconds:(cost) 97658三、结论
很难看出差别, 主要耗时集中在random,打算提前生成好数据并增加数据长度再测一下,日后有空继续补充。



