Skip to content
Snippets Groups Projects
Verified Commit 377278e8 authored by orestis.malaspin's avatar orestis.malaspin
Browse files

added sum code to measure CPU time

parent 82eaaad1
Branches
No related tags found
No related merge requests found
Pipeline #14779 passed
sum
CC:=gcc
# SAN:=-fsanitize=address
CFLAGS:=-Wall -Wextra -pedantic -g $(SAN)
LDFLAGS:=-lm $(SAN)
EXECS := $(shell find . -type f -iname '*.c' | sed 's/\.c//g')
all: $(EXECS)
$(EXECS): %: %.c
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
@echo $@ >> .gitignore
.PHONY: clean all
clean:
rm -f *.o $(EXECS) .gitignore
#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;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment