Guest User

Vector average

a guest
Jul 9th, 2015
238
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <sys/time.h>
  2. #include <sys/param.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <xmmintrin.h>
  7.  
  8. typedef float dot[4];
  9. #define N 100000000
  10.  
  11. double gettime ()
  12. {
  13.     struct timeval tv;
  14.     gettimeofday (&tv, 0);
  15.     return (double)tv.tv_sec + (0.000001 * (double)tv.tv_usec);
  16. }
  17.  
  18. void calc_avg1 (dot res, const dot array[], int n)
  19. {
  20.     int i,j;
  21.     memset (res, 0, sizeof (dot));
  22.     for (i = 0; i < n; i++)
  23.     {
  24.         for (j = 0; j<4; j++) res[j] += array[i][j];
  25.     }
  26.     for (j = 0; j<4; j++) res[j] /= n;
  27. }
  28.  
  29. void calc_avg2 (dot res, const dot array[], int n)
  30. {
  31.     int i;
  32.     __v4sf r = _mm_set1_ps (0.0);
  33.     for (i=0; i<n; i++) r += _mm_load_ps (array[i]);
  34.     r /= _mm_set1_ps ((float)n);
  35.     _mm_store_ps (res, r);
  36. }
  37.  
  38. int main ()
  39. {
  40.     void *space = malloc (N*sizeof(dot)+15);
  41.     dot *array = (dot*)(((unsigned long)space+15) & ~(unsigned long)15);
  42.     dot avg __attribute__((aligned(16)));
  43.     int i;
  44.     double time;
  45.  
  46.     for (i = 0; i < N; i++)
  47.     {
  48.         array[i][0] = 1.0*random();
  49.         array[i][1] = 1.0*random();
  50.         array[i][2] = 1.0*random();
  51.     }
  52.     time = gettime();
  53.     calc_avg1 (avg, array, N);
  54.     time = gettime() - time;
  55.     printf ("%f\n%f %f %f\n", time, avg[0], avg[1], avg[2]);
  56.  
  57.     time = gettime();
  58.     calc_avg2 (avg, array, N);
  59.     time = gettime() - time;
  60.     printf ("%f\n%f %f %f\n", time, avg[0], avg[1], avg[2]);
  61.     return 0;
  62. }
RAW Paste Data