-
orestis.malaspin authoredorestis.malaspin authored
sum.c 907 B
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000000
#define NUM_TIMES 10
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 of %f took about %.5f seconds\n", s,
(((double)tend.tv_sec + 1e-9 * tend.tv_nsec) -
((double)tstart.tv_sec + 1e-9 * tstart.tv_nsec)) /
NUM_TIMES);
return 0;
}