Last active
January 9, 2021 09:29
-
-
Save kawakami-o3/7c8aa1e63018bb3427a382904de1ce17 to your computer and use it in GitHub Desktop.
Array vs List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<time.h> | |
#define N 10000 | |
#define TRIAL 10000 | |
typedef struct Cell { | |
int value; | |
struct Cell *next; | |
} Cell; | |
Cell *make_cell(int i) { | |
Cell *c = malloc(sizeof(Cell)); | |
c->value = i; | |
c->next = NULL; | |
return c; | |
} | |
int main(void) { | |
Cell *cells[N]; | |
int v = 1; | |
for (int i=0; i<N; i++) { | |
cells[i] = make_cell(v); | |
v *= -1; | |
} | |
//for (int i=0; i<N; i++) { | |
// cells[i] = make_cell(i); | |
//} | |
for (int i=0; i<N-1; i++) { | |
cells[i]->next = cells[i+1]; | |
} | |
{ | |
long start = clock(); | |
for (int j=0; j<TRIAL; j++) { | |
int sum = 0; | |
for (int i=0; i<N; i++) { | |
sum += cells[i]->value; | |
} | |
//printf("%d\n", sum); | |
} | |
printf("%f s\n", (double)(clock() - start)/CLOCKS_PER_SEC); | |
} | |
{ | |
long start = clock(); | |
for (int j=0; j<TRIAL ; j++) { | |
int sum = 0; | |
Cell *cur = cells[0]; | |
do { | |
sum += cur->value; | |
cur = cur->next; | |
} while (cur != NULL); | |
//printf("%d\n", sum); | |
} | |
printf("%f s\n", (double)(clock() - start)/CLOCKS_PER_SEC); | |
} | |
return 0; | |
} |
Author
kawakami-o3
commented
Jan 9, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment