Last active
February 7, 2018 14:50
-
-
Save piotrMocz/158efc264503d5e487263e092985f656 to your computer and use it in GitHub Desktop.
Testing the performance of populating an array with structs.
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 10000000 | |
typedef struct _Foo { | |
int name, id; | |
} Foo; | |
// Foo nodesGlobal[N]; | |
void printUC(Foo uc) { | |
printf("Foo { name = %d, id = %d }\n", uc.name, uc.id); | |
} | |
// allocate the memory chunk to fit n structs | |
Foo *allocFoos(long n) { | |
return (Foo *) malloc(n * sizeof(Foo)); | |
} | |
// populate the array with structs: | |
void createFoos(Foo *v, long n) { | |
for (long i = 0; i < n; ++i) { | |
v[i].name = i; | |
v[i].id = i + 1; | |
} | |
} | |
void benchmark(const char *name, Foo *v, long n) { | |
printf("[[ %s ]]", name); | |
clock_t begin = clock(); | |
time_t begin_wall = time(NULL); | |
createFoos(v, n); | |
clock_t end = clock(); | |
time_t end_wall = time(NULL); | |
double elapsed = ((double) (end - begin)) / CLOCKS_PER_SEC * 1000; | |
double elapsed_wall = ((double) (end - begin)) / 1000; | |
printf("Time taken: %lf ms (cpu) %lf ms (wall)\n", elapsed, elapsed_wall); | |
} | |
int main() { | |
printf("%s", "Starting the benchmark\n"); | |
Foo *nodes = allocFoos(N); | |
benchmark("Malloced-array", nodes, N); | |
free(nodes); | |
printf("%s", "Done\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment