Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // gcc -Wall -std=c99 -Ofast -march=native loop-optimization.c -o loop
- // http://www.lshift.net/blog/2013/11/27/optimizing-loops-in-c-for-higher-numerical-throughput-and-for-fun
- #include <stdint.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #define COLS (16)
- #define ROWS (1000)
- #define COUNT (100000)
- float globalSrc[ROWS][COLS];
- float globalDst[ROWS];
- // sum[0] = sum(vec[0][0..COLS-1]^2)
- // sum[1] = sum(vec[1][0..COLS-1]^2)
- // sum[2] = sum(vec[2][0..COLS-1]^2)
- // ...
- // sum[ROWS] = sum(vec[ROWS][0..COLS-1]^2)
- void sum_of_squares_0(float dst[ROWS], float src[ROWS][COLS]) {
- for (size_t x = 0; x < COLS; x++) {
- for (size_t y = 0; y < ROWS; y++) {
- dst[y] += src[y][x] * src[y][x];
- }
- }
- }
- void sum_of_squares_1(float dst[ROWS], float src[ROWS][COLS]) {
- for (size_t y = 0; y < ROWS; y++) {
- for (size_t x = 0; x < COLS; x++) {
- dst[y] += src[y][x] * src[y][x];
- }
- }
- }
- // total = vec[0..ROWS]
- double sum_of_sums(float sum[ROWS]) {
- double total = 0.0;
- for (int y = 0; y < ROWS; y++) {
- // printf("%d: %f\n", y, sum[y]);
- total += sum[y];
- }
- return total;
- }
- // vec[0..COLS] = [0..COLS]
- void init_vector(float vec[COLS]) {
- for (int i = 0; i < COLS; i++) {
- vec[i] = (float) i;
- }
- }
- typedef void (*sum_of_squares_t)(float dst[ROWS], float src[ROWS][COLS]);
- int main(int argc, char **argv) {
- if (argc <= 1) {
- printf("Usage: %s num\n", argv[0]);
- return 1;
- }
- sum_of_squares_t sum_func;
- if (*argv[1] == '0') sum_func = sum_of_squares_0;
- else if (*argv[1] == '1') sum_func = sum_of_squares_1;
- else {
- printf("Function '%s' not recognized.\n", argv[1]);
- return 1;
- }
- for (size_t y = 0; y < ROWS; y++) {
- init_vector(&globalSrc[y][0]);
- }
- for (size_t n = 0; n < COUNT; n++) {
- memset(globalDst, 0, ROWS * sizeof(*globalDst));
- sum_func(globalDst, globalSrc);
- }
- double total = sum_of_sums(globalDst);
- printf("Total: %lf (%d iterations)\n", total, COUNT);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment