diff --git a/source_codes/complexity/.gitignore b/source_codes/complexity/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..92292873f791ed576373b70f2bd8011aa701bf90 --- /dev/null +++ b/source_codes/complexity/.gitignore @@ -0,0 +1 @@ +sum diff --git a/source_codes/complexity/Makefile b/source_codes/complexity/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d7822ac93c5aaf6b38512758abde6dae01881871 --- /dev/null +++ b/source_codes/complexity/Makefile @@ -0,0 +1,18 @@ +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 + diff --git a/source_codes/complexity/sum.c b/source_codes/complexity/sum.c new file mode 100644 index 0000000000000000000000000000000000000000..4451354467ea6177e971f5fbc83a1e9122ea44f2 --- /dev/null +++ b/source_codes/complexity/sum.c @@ -0,0 +1,39 @@ +#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; +}