在C/C++代码中使用SSE等指令集的指令(5)SSE进行加法运算简单的性能测试

来源:互联网 发布:天谕女角色捏脸数据 编辑:程序博客网 时间:2024/05/20 12:23

下面是一个简单的测试SSE指令性能的程序,可以看到明显的性能提升。

(说明:程序中的timing.h使用的是http://blog.csdn.net/gengshenghong/article/details/6973086中介绍的时间间隔获取方法)

[cpp] view plain copy print?
  1. #define WIN  
  2. #include "timing.h"  
  3. #include <intrin.h>  
  4. #include <stdlib.h>  
  5. #include <math.h>  
  6.   
  7. #define N 4*100000      // 注意:必须是4的倍数,否则使用SSE指令计算,要进行一些处理,从而保证正确。  
  8. _MM_ALIGN16 float op1[N];  
  9. _MM_ALIGN16 float op2[N];  
  10. _MM_ALIGN16 float result1[N];  
  11. _MM_ALIGN16 float result2[N];  
  12.   
  13. void init()  
  14. {  
  15.     for(int i = 0;i < N; i++)  
  16.     {  
  17.         op1[i] = (float)rand()/(float)RAND_MAX;  
  18.         op2[i] = (float)rand()/(float)RAND_MAX;  
  19.     }  
  20. }  
  21.   
  22. void checkResult(int debug)  
  23. {  
  24.     bool isSame = true;  
  25.     for(int i = 0;i < N; i++)  
  26.     {  
  27.         if (debug)  
  28.         {  
  29.             printf("%lf     %lf\n", result1[i], result2[i]);  
  30.         }  
  31.         else  
  32.         {  
  33.             if (fabs(result1[i] - result2[i]) > 0.000001)  
  34.             {  
  35.                 isSame = false;  
  36.                 break;  
  37.             }  
  38.         }  
  39.     }  
  40.     if (!debug) {  
  41.         if (isSame)  
  42.             printf("Result is Same\n");  
  43.         else  
  44.             printf("Result is not same\n");  
  45.     }  
  46. }  
  47.   
  48. void add1()  
  49. {  
  50.     for(int i = 0; i < N;i++)  
  51.         result1[i] = op1[i] + op2[i];  
  52. }  
  53.   
  54. void add2()  
  55. {  
  56.     __m128  a;  
  57.     __m128  b;  
  58.     __m128  c;  
  59.   
  60.     for(int i = 0; i < N;i = i + 4)  
  61.     {  
  62.         // Load  
  63.         a = _mm_load_ps(op1 + i);  
  64.         b = _mm_load_ps(op2 + i);  
  65.   
  66.         c = _mm_add_ps(a, b);   // c = a + b  
  67.   
  68.         _mm_store_ps(result2 + i, c);  
  69.     }  
  70. }  
  71.   
  72. int main(int argc, char* argv[])  
  73. {  
  74.     init();  
  75.     srand((unsigned int)time(NULL));  
  76.   
  77.     printf("Add a vector:\n");  
  78.     startTiming();  
  79.     add1();  
  80.     stopWithPrintTiming();  
  81.   
  82.     printf("\n");  
  83.     printf("Add a vector with SSE instructions:\n");  
  84.     startTiming();  
  85.     add2();  
  86.     stopWithPrintTiming();  
  87.   
  88.     printf("\n");  
  89.     checkResult(0);  
  90.   
  91.     return 0;  
  92. }  
0 0
原创粉丝点击