From 377278e859785d56a8b21e5c200175390f6a645e Mon Sep 17 00:00:00 2001
From: Orestis <orestis.malaspinas@pm.me>
Date: Wed, 27 Oct 2021 10:39:33 +0200
Subject: [PATCH] added sum code to measure CPU time

---
 source_codes/complexity/.gitignore |  1 +
 source_codes/complexity/Makefile   | 18 ++++++++++++++
 source_codes/complexity/sum.c      | 39 ++++++++++++++++++++++++++++++
 3 files changed, 58 insertions(+)
 create mode 100644 source_codes/complexity/.gitignore
 create mode 100644 source_codes/complexity/Makefile
 create mode 100644 source_codes/complexity/sum.c

diff --git a/source_codes/complexity/.gitignore b/source_codes/complexity/.gitignore
new file mode 100644
index 0000000..9229287
--- /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 0000000..d7822ac
--- /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 0000000..4451354
--- /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;
+}
-- 
GitLab