Skip to content
Snippets Groups Projects
Select Git revision
  • 85e7981251183b1da785a78bf9a81ddfe0a156eb
  • main default protected
2 results

sum.c

Blame
  • sum.c 944 B
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #ifndef SIZE
    #define SIZE 1000000
    #endif
    
    #ifndef NUM_TIMES
    #define NUM_TIMES 10
    #endif
    
    void init(int n, double tab[]) {
        for (int i = 0; i < n; ++i) {
            tab[i] = (double)rand() / (double)RAND_MAX;
        }
    }
    
    double sum(int n, double tab[]) {
        double s = tab[0];
        for (int i = 1; i < n; ++i) {
            s += tab[i] * tab[i] * tab[i] * tab[i];
        }
        return s;
    }
    
    int main() {
        double tab[SIZE];
        init(SIZE, tab);
    
        struct timespec tstart = {0, 0}, tend = {0, 0};
        clock_gettime(CLOCK_MONOTONIC, &tstart);
        double s = 0;
        for (int i = 0; i < NUM_TIMES; ++i) {
            s += sum(SIZE, tab);
        }
        clock_gettime(CLOCK_MONOTONIC, &tend);
        printf("the computation took about %.5f seconds\n",
            (((double)tend.tv_sec + 1e-9 * tend.tv_nsec) -
                ((double)tstart.tv_sec + 1e-9 * tstart.tv_nsec)) /
                NUM_TIMES);
    
        return 0;
    }