/** * One final C program coverying a huge amount of ground * @author gtowell * Created: May 9, 2021 * **/ #include #include #include //Formatting for data output #define CCOLUMN "%2d %9ld %8.3f\n" #ifndef NULL #define NULL (void *)0 #endif //function pointer typedef typedef void(*funs)(long); //array of function pointers funs funarray[4]; /** * First worker function * Just do standard array stuff * @param cnt the amount of work to do. * **/ void work1(long cnt) { long arr[cnt]; for (int i = 0; i < cnt; i++) { for (int j = 0; j < cnt; j++) { arr[i] += j; } } } /** * First worker function. Half way to full pointer bliss * Just do standard array stuff * @param cnt the amount of work to do. * **/ void work1b(long cnt) { long arr[cnt]; for (int i = 0; i < cnt; i++) { int *p = (int *)arr; for (int j = 0; j < cnt; j++) { *(p++) += j; } } } /** * Second worker function * Just do stuff very similar to worker1, but do it all with pointers * @param cnt the amount of work to do. * **/ void work2(long cnt) { long *arr = malloc(cnt * sizeof(long)); long *last = arr + cnt; for (int i = 0; i < cnt; i++) { long *p = arr; while (1) { *(p++) += i; if (p==last) break; } } free(arr); } typedef struct ll { int val; struct ll *next; } ll; /** * Third worker function * Again, similar to work1, but in linkedlist style * @param cnt the amout of work to do * **/ void work3(long cnt) { ll *head = NULL; for (int i = 0; i < cnt; i++) { if (i==0) { //In the first loop, set of the linked list head = malloc(1 * sizeof(ll)); ll *this = head; for (int j = 0; j < cnt; j++) { this->next = malloc(1 * sizeof(ll)); this->val = i; this = this->next; this->next = NULL; } } else { ll *this = head; for (int j = 0; j < cnt; j++) { this->val += j; this = this->next; } } } while (head != NULL) { ll *nxt = head->next; free(head); head = nxt; } } int main(int argc, char const *argv[]) { funarray[0] = work1; funarray[1] = work1b; funarray[2] = work2; funarray[3] = work3; clock_t start, end; start = clock(); int funsel = atoi(argv[1]); int funwork = atol(argv[2]); funarray[funsel](funwork); end = clock(); float cpu_time_used = ((float) (end - start)) / CLOCKS_PER_SEC; printf(CCOLUMN, funsel, funwork, cpu_time_used ); return 0; }