Guest User

loop-optimization.c

a guest
Dec 16th, 2013
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | None | 0 0
  1. // gcc -Wall -std=c99 -Ofast -march=native loop-optimization.c -o loop
  2. // http://www.lshift.net/blog/2013/11/27/optimizing-loops-in-c-for-higher-numerical-throughput-and-for-fun
  3.  
  4. #include <stdint.h>
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8.  
  9. #define COLS (16)
  10. #define ROWS (1000)
  11. #define COUNT (100000)
  12.  
  13. float globalSrc[ROWS][COLS];
  14. float globalDst[ROWS];
  15.  
  16.  
  17. // sum[0] = sum(vec[0][0..COLS-1]^2)
  18. // sum[1] = sum(vec[1][0..COLS-1]^2)
  19. // sum[2] = sum(vec[2][0..COLS-1]^2)
  20. // ...
  21. // sum[ROWS] = sum(vec[ROWS][0..COLS-1]^2)
  22. void sum_of_squares_0(float dst[ROWS], float src[ROWS][COLS]) {
  23.     for (size_t x = 0; x < COLS; x++) {
  24.         for (size_t y = 0; y < ROWS; y++) {
  25.             dst[y] += src[y][x] * src[y][x];
  26.         }
  27.     }
  28. }
  29.  
  30.  
  31. void sum_of_squares_1(float dst[ROWS], float src[ROWS][COLS]) {
  32.     for (size_t y = 0; y < ROWS; y++) {
  33.         for (size_t x = 0; x < COLS; x++) {
  34.             dst[y] += src[y][x] * src[y][x];
  35.         }
  36.     }
  37. }
  38.  
  39. // total = vec[0..ROWS]
  40. double sum_of_sums(float sum[ROWS]) {
  41.     double total = 0.0;
  42.     for (int y = 0; y < ROWS; y++) {
  43.         //        printf("%d: %f\n", y, sum[y]);
  44.         total += sum[y];
  45.     }
  46.     return total;
  47. }
  48.  
  49. // vec[0..COLS] = [0..COLS]
  50. void init_vector(float vec[COLS]) {
  51.     for (int i = 0; i < COLS; i++) {
  52.         vec[i] = (float) i;
  53.     }
  54. }
  55.  
  56. typedef void (*sum_of_squares_t)(float dst[ROWS], float src[ROWS][COLS]);
  57.  
  58. int main(int argc, char **argv) {
  59.  
  60.     if (argc <= 1) {
  61.         printf("Usage: %s num\n", argv[0]);
  62.         return 1;
  63.     }
  64.  
  65.     sum_of_squares_t sum_func;
  66.     if (*argv[1] == '0') sum_func = sum_of_squares_0;
  67.     else if (*argv[1] == '1') sum_func = sum_of_squares_1;
  68.     else {
  69.         printf("Function '%s' not recognized.\n", argv[1]);
  70.         return 1;
  71.     }
  72.  
  73.  
  74.     for (size_t y = 0; y < ROWS; y++) {
  75.         init_vector(&globalSrc[y][0]);
  76.     }
  77.  
  78.     for (size_t n = 0; n < COUNT; n++) {
  79.         memset(globalDst, 0, ROWS * sizeof(*globalDst));
  80.         sum_func(globalDst, globalSrc);
  81.     }
  82.  
  83.     double total = sum_of_sums(globalDst);
  84.     printf("Total: %lf (%d iterations)\n", total, COUNT);
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment